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];
jQuery.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 };
jQuery.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) {
		// do stuff
		console.log(name + '=' + value);
	});
});
// outputs: red=#f00 green=#0f0 blue=#00f
})(jQuery);

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="">