10

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?

Ryre
  • 6,135
  • 5
  • 30
  • 47
  • No, it's not possible like that. Here's an existing SO discussion about this: http://stackoverflow.com/questions/2002394/jquery-animate-each-chaining – davidethell Jan 25 '12 at 20:08

4 Answers4

36

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:

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • 3
    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 Mar 25 '13 at 16:00
9

$.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');
1

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

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

does the job.

MaxH
  • 859
  • 10
  • 14
1

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

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91