Yep, jquery functions apply themselves to all the elements you
selected. You only need to use each command if you need to do your own
custom handling... Likeeee um,

$("li").each(function(idx){
   $(this).css('background-color', '#' + idx + idx + idx);
});

Ok, bad example (this sets the background color to a gray scale value
relevant to the item's index) ... but you'll often need to do custom
stuff that there isn't a jQUery command for (hence the fifty zillion
plugins available: nearly all of which use "each" to process each
node).

Also, the built in commands use "each" internally: for example, here
is a (slightly edited for clarity) snippet from the jquery core:
jQuery.fn[ "toggleClass" ] = function(){
        return this.each( function(){ ...function to toggle class... },
arguments );
};

On Sep 16, 2:30 am, Timid <da...@pointdesign.info> wrote:
> I'm a noob trying to get a better understanding of Jquery and have a
> simple question about the each() function.
>
>    $("li").click(function () {
>       $("li").each(function(){
>         $(this).toggleClass("example");
>       });
>     });
>
>    $("li").click(function () {
>       $("li").toggleClass("example");
>       });
>
> What is the added value of using each() in the top example when the
> bottom example does the job just fine. Why would you want to use each?

Reply via email to