Ryre
Ryre

Reputation: 6181

jQuery each element

I'm curious why this code is invalid:

$.each( $("p") ).css("color", "green");


While this code works fine:

$.each($("p"), function() { $(this).css("color", "green") });


Is it not possible to chain elements with each?

Upvotes: 10

Views: 54532

Answers (4)

MaxH
MaxH

Reputation: 859

Note that no version of each is needed to achieve the (most likely) desired effect.

$("p").css("color", "green");

does the job.

Upvotes: 1

Rob W
Rob W

Reputation: 348972

Remove the wrapper:

$("p").css("color", "green");

If you want to use $.each, specify a function as a second argument:

$("p").each(function() {
//Or: $.each( $("p"), function() {
   $(this).css("color", "green");
});

The jQuery method automatically returns an instance of the collection, so chaining should still be possible.

Demo: http://jsfiddle.net/pC2Bj/

See also:

Upvotes: 36

user1106925
user1106925

Reputation:

$.each() requires a function as the second argument. You've only passed one argument.

http://api.jquery.com/jquery.each/

jQuery.each( collection, callback(indexInArray, valueOfElement) )

collection The object or array to iterate over.

callback(indexInArray, valueOfElement) The function that will be executed on every object.


Yes, it is possible to chain, since $.each returns the collection you're iterating.

$.each($("p"), function() { $(this).css("color", "green") }).addClass('test');

Upvotes: 9

FishBasketGordo
FishBasketGordo

Reputation: 23132

$.each requires two parameters, the second being a callback that executes once for each element. If you don't pass the callback parameter, $.each won't work.

Also, $.each returns the object over which it iterates, so chaining doesn't work like it would with methods that return a jQuery object.

Upvotes: 1

Related Questions