jQuery each

Adding index number to each chosen element:

// DOM elements
$("div").each(function(index, value) {
	console.log('div' + index + ':' + $(this).attr('id'));
	// outputs: div1:header, div2:body, div3:footer
});
 
 
// arrays
var numberArray = [0,1,2,3,4,5];
$.each(numberArray , function(index, value){
 	console.log(index + ':' + value);
	// outputs: 1:1 2:2 3:3 4:4 5:5
});
 
 
// objects
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(i, val) {
	console.log(val);
	// outputs: 1 2 3 4 5
});
 
 
// json
(function($) {
	var json = [
		{ "red": "#f00" },
		{ "green": "#0f0" },
		{ "blue": "#00f" }
	];
	$.each(json, function() {
		$.each(this, function(name, value) {
			console.log(name + '=' + value);
			// outputs: red=#f00 green=#0f0 blue=#00f
		});
	});
});
VN:F [1.9.17_1161]
Rating: 0 (from 0 votes)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">