web-profile

jQuery each

Adding index number to each chosen element:

// DOM caching
var $comments = $('.comment');
$.each($comments, function(index, comment) {
    var $comment =  $(comment);
    $comment.find('.comment_ratings').remove();
    //console.log('comment log: ',$comment);
});

// 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
		});
	});
});

Leave a Reply

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