The Beauty Of The jQuery Each() Method

Posted February 19, 2007 at 4:48 PM

Tags: Javascript / DHTML

The jQuery library provides a method, Each(), which will loop through each element of the target jQuery object:

 Launch code in new window » Download code as text file »

  • // Loop over each hottie.
  • $( "#girls a.hottie" ).each(
  •  
  • // For each hottie, run this code. The "indIndex" is the
  • // loop iteration index on the current element.
  • function( intIndex ){
  •  
  • // Bind the onclick event to simply alert the
  • // iteration index value.
  • $( this ).bind (
  • "click",
  • function(){
  • alert( "Hottie index: " + intIndex );
  • }
  • );
  •  
  • }
  •  
  • );

While there is nothing revolutionary going on here (although the "Bind" method is freakin' sweet-ass-sweet unto itself), the beauty of the Each() method is that it creates a separate function scope for each loop iteration. For anyone who has tried to do a standard FOR-Loop in which each iteration tries to dynamically set some object value, you probably have run into situation where all values post-loop are the same. This has to do with when the variable is being bound.

By creating a separate function scope for each loop iteration, you basically eliminate all the "unexpected" variable binding behavior. Sweet! It seems every time I step back and look at what jQuery is doing for me, it's simply stripping away more and more headache time.

Download Code Snippet ZIP File

Post Comment  |  Ask Ben  |  Permalink  |  Other Searches  |  Print Page




Learning ColdFusion 9 - ColdFusion 9 tutorials, samples, examples, demos

Reader Comments

Feb 19, 2007 at 9:40 PM // reply »
33 Comments

Yes indeed, each() rules. If you get excited about this kind of stuff, you may want to take a look at Ruby on Rails if you haven't already done so. You'll get excited about a lot of things. For one, the Ruby language alone has some very powerful features that are quite unique and that allow for very elegant code. I really like ColdFusion, but I think RoR brings a lot to the table and it costs nothing (OK, I know, our time is valuable) to give it a try and see something different. And if you decide to do so, please be sure to let us all know what you thought!


Feb 19, 2007 at 11:30 PM // reply »
6,351 Comments

Thomas,

Thanks for the heads up. To date, I have not looked into Ruby on Rails. However, I have heard a lot of good things about it. When I start to look into it, I am sure I will have a lot to say ;)


Matt
Mar 22, 2007 at 6:00 AM // reply »
1 Comments

Great Code.

Thanks


gt
Jul 20, 2007 at 11:50 PM // reply »
1 Comments

exactly what i was looking for. this should be a jquery tutorial. thanks.


Snowcore
Jul 1, 2008 at 11:30 AM // reply »
1 Comments

I like it, because of possiblity to work with associative arrays - it's really powerful!


Sergey
Oct 30, 2008 at 1:30 PM // reply »
1 Comments

Double thanks!
First - for Each(), another one - for $(this), both helped me a lot!


goody
Dec 18, 2008 at 9:59 AM // reply »
1 Comments

Wow. Thank you. I'm fairly new to js/jquery and this really helps me with logically thinking/looking at what I need. Plus it really helps me in a current project.


Dec 19, 2008 at 3:17 PM // reply »
6,351 Comments

@Goody,

I think you are really gonna love jQuery. It rocks and will make Javascript development much easier!


chrononaut
Mar 12, 2009 at 2:16 AM // reply »
1 Comments

Oh my, you just saved me what I'm sure would have been a few more hours of searching. The each() function is great but I couldn't find any documentation anywhere regarding getting an index from it until here. So thank you. I like jQuery but IE doesn't play nice.


A geek girl
Jun 1, 2009 at 4:26 PM // reply »
1 Comments

Thanks for assuming that I don't exist


Jun 2, 2009 at 8:28 AM // reply »
6,351 Comments

@A Geek Girl,

I am not sure what you are referring to?


greg
Jun 8, 2009 at 9:53 PM // reply »
1 Comments

hey

I want to use each() to manipulate all the checkboxes that match.

my head and the wall are both bloody now, i seem to need to use this.checked i.o. $(this)
typeof($(this)) yields 'object object'

anyone care to enlighten me?

$('.myclass').each(
function ( intindex ){
this.checked =chkbox.checked ;
}
);

does work. (thanks alot for that btw). Just trying to understand why it works, lol.

how does my function know what this is? i have lots of user myths building up in my head....

thanks again


Jun 9, 2009 at 8:18 AM // reply »
6,351 Comments

@greg,

When jQuery executes the function that you pass to the each() method, it executes it in the context of given object such that "this" is explicitly pointed to the given object. This is what the call() and apply() methods do in Javascript.

Most likely, they do something like this:

for (i = 0 ; i < this.size() ; i++){
. . . . yourCallback.call( this[ i ], i, this[ i ] );
}

The first argument of the call() method is the this/context of the executing function (yourCallback). Any subsequent arguments (i, this[ i ]) are the actual arguments passed to the method.


Jul 21, 2009 at 9:53 PM // reply »
1 Comments

Thanks for this.


Aug 7, 2009 at 3:24 PM // reply »
1 Comments

You're a Funkin Guy... Everythin I search in google I get you blog... Thanks Ben!


Aug 7, 2009 at 4:42 PM // reply »
6,351 Comments

@Roberto,

Ha ha, thanks man - just glad that I'm putting some good stuff out tehre.


Joshua Gonzalez
Aug 7, 2009 at 6:19 PM // reply »
3 Comments

This is some real good stuff right here. You got to love Jquery


George Garchagudashvili
Aug 20, 2009 at 5:39 AM // reply »
1 Comments

Hey Ben how are you?
very good stuff here, it helped to much...
Nice photos too...
Thanks


ABCD
Aug 28, 2009 at 6:27 AM // reply »
1 Comments

There is some functionality mistakes in this girl.hottie example.

plz replace alert with f***.

Thanks.


EFGH
Aug 31, 2009 at 8:49 PM // reply »
1 Comments

@ABCD

That would require that us programmers actually talk to girls, which (*adjusts glasses*) is simply ridiculous.

In seriousness, thanks for the write-up, Ben.


Sep 2, 2009 at 8:41 AM // reply »
6,351 Comments

@George, @EFGH,

No problem guys, glad to help.


Sep 6, 2009 at 10:55 PM // reply »
1 Comments

Hey Ben,

Good lookin' blog for a developer :P

Relating to each(), have you got any tips on not getting this outputting a 'continue reading' link for EVERY <p>, but the whole bunch of <p>'s in the post?

http://pastebin.com/m6a6da785

Example here: http://test.ldexterldesign.co.uk/?page_id=9 (disable CSS and you'll see what I mean: http://twitpic.com/gsxsk)

Thanks,
L


Sep 13, 2009 at 7:47 AM // reply »
6,351 Comments

@Lewis,

I think the problem is that you are calling each() on your P tags. What you want to do is get the collection of P tag and then get the text() on the entire set.

var text = $( ".... p" ).text();

This will return the text aggregation of all the paragraphs found in the set. This way, you don't have to loop over the 2 paragraphs, which is why you are getting two read more links.


ArthasMX
Oct 8, 2009 at 7:37 PM // reply »
1 Comments

Wow! now i understand "each()"!! i've had read a lot about it, but using "common names"....but it was hard to understand.

With this example: "girls.hottie", was so really easy to understand hehehehe

thanks!

@A GEEK GIRL: hehehe


Oct 31, 2009 at 4:35 PM // reply »
6,351 Comments

@ArthasMX,

Excellent - glad I could explain this in a way that finally made sense.


Post Comment  |  Ask Ben

Recent Blog Comments
ziggy
Nov 4, 2009 at 12:30 AM
A Moment That Touched Me - The Fountainhead
>>Academia is full of liberals who abhor Ayn Rand. Like all the phil profs doing "conservatives" like Plato, Kant, Heidegger, Strauss, etc? Philosophy - which she claims to do - has nothing t ... read »
JC
Nov 3, 2009 at 11:08 PM
A Moment That Touched Me - The Fountainhead
Is this a Philosophy forum or a jQuery forum?? Either way I like talking about both :) good post, haven't read the book but it definitely sounds like a book I would like to get my hands on. jQuery an ... read »
Nov 3, 2009 at 10:55 PM
Project HUGE: Active Release Technique (ART) With Dr. Christopher Anselmi In NYC
A peaceful mind and body keeps a man happy.Muscle release techniques are employed to people with severe sports injuries and stress pains.A great websites offers a wide range of muscle release techniq ... read »
Nov 3, 2009 at 10:54 PM
jQuery Demo: Creating A Sliding Image Puzzle Plug-In
Very nice list, thank you. http://www.likespy.com/ ... read »
Nov 3, 2009 at 10:26 PM
IIS MOD-Rewrite: R6016 Not Enough Space For Thread Data
Very nice list, thank you. ... read »
Nov 3, 2009 at 7:34 PM
Dude! I just posted this!
Just upgraded my URL handler... testing. ... read »
Mike Leung
Nov 3, 2009 at 7:23 PM
A Moment That Touched Me - The Fountainhead
re: Cooljj: Any example of Rand's "genius" anyone has ever cared to share that I've seen -- like Roarke calling someone a fool completely overlooking how he's demonstrating as much concern over what ... read »
Nov 3, 2009 at 6:28 PM
Making ColdFusion's QueryNew() More Readable
No - but I will now, just got to figure it out, never used WDDX method before. ... read »