Sumeet
Sumeet

Reputation: 925

Why we should use $().each method?

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

Answers (3)

Scary Wombat
Scary Wombat

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

Rajesh
Rajesh

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

Archy Will He
Archy Will He

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

Related Questions