Take the 2-minute tour ×

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?

share|improve this question
No, it's not possible like that. Here's an existing SO discussion about this: stackoverflow.com/questions/2002394/… –  davidethell Jan 25 '12 at 20:08
add comment

3 Answers

up vote 22 down vote accepted

Remove the wrapper:

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

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

//Or: $.each( $("p"), function() {

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

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

See also:

share|improve this answer
It should be noted that $.each is used for HTMLCollections and other native JavaScript collections while the jQuery method $('.selector').each() is used for jQuery objects. –  Sethen Maleno Mar 25 '13 at 16:00
add comment

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


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

collection The object or array to iterate over.


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

$.each($("p"), function() { $(this).css("color", "green") }).addClass('test');
share|improve this answer
Could you give an example of chaining each? –  Toast Jan 25 '12 at 20:15
@Toast: Updated with an example. –  squint Jan 25 '12 at 20:16
@Toast. I wish you were right, But my answer was wrong. See this JSFiddle –  gdoron Jan 25 '12 at 20:43
add comment

$.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.

share|improve this answer
add comment

Your Answer


