Reputation: 925
Probably a very basic, but still need to know insite.
For a simple DOM operation, what can force us to use Jquery -> .each ?
Basically, What's the difference between following two?
$('ul').css('color','black')
AND
$('ul').each(function(){ $(this).css('color','black');});
What is recommended and why?
Upvotes: 0
Views: 73
Reputation: 44854
.each is useful in situations where you want to iterate over each element seperately
$( "div" ).each(function( i ) {
if ( this.style.color !== "blue" ) {
this.style.color = "blue";
} else {
this.style.color = "";
}
});
or
$("div").css("color", function(i, val){return val === "blue" ? "" : "blue"});
Upvotes: 3
Reputation: 3778
To iterate over list of objects, you can use $.each(). Very useful if u get a json string or object from ajax call, and then need to iterate over it.
Upvotes: -1
Reputation: 9787
.each
will be useful in situations like this:
var a = 100;
$('ul').each(function(){ $(this).css('width',a+'px'); a+=200;});
Upvotes: 3