JQuery each element

jquery

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?

Best Solution

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: