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,516 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 ;)


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.


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!


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

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


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,516 Comments

@Goody,

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


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.


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,516 Comments

@A Geek Girl,

I am not sure what you are referring to?


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,516 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 »
2 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,516 Comments

@Roberto,

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


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

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


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


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.


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,516 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,516 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.


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,516 Comments

@ArthasMX,

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


Post Comment  |  Ask Ben

Recent Blog Comments
Nov 20, 2009 at 11:32 PM
Five Months Without Hungarian Notation And I'm Loving It
I've used headless camel case for years for not only ColdFusion variables, but also SQL tables and fields... pretty much everything involving code. I also subscribe to the "don't abbreviate and clea ... read »
Nov 20, 2009 at 11:00 PM
Five Months Without Hungarian Notation And I'm Loving It
@Marcel, Yeah, I always err on the side of longer but more readable variable names. As for the camel casing of CF methods and the headless camel casing of custom items, I get around this by always ... read »
Nov 20, 2009 at 10:56 PM
Five Months Without Hungarian Notation And I'm Loving It
I use the following and love it: my.namespace.MyComponents.functionMethodsOrUDF() CONSTANT_VALUES_OR_PROPERTIES One thing I always try is to CamelCaseBuiltInColdFusionFunctions() so others can tell ... read »
Nov 20, 2009 at 5:38 PM
Learning ColdFusion 8: CFImage Part I - Reading And Writing Images
Hi Ben, Great article. I've been looking around to see if ColdFusion image engine can programatically create the following "wrap around" effect: http://www.creativepro.com/article/photoshop-s-she ... read »
Nov 20, 2009 at 5:35 PM
Maintaining ColdFusion Sessions Across SMS Text Message Requests Without Cookies
@Dave: I talked to Gert he suggested: <cfhttp method="get" url="http://{some cf website}" result="stuff" addtoken="yes" /> Note the addition of cfhttp attribute addtoken. That should persist y ... read »
Nov 20, 2009 at 5:23 PM
Maintaining ColdFusion Sessions Across SMS Text Message Requests Without Cookies
@Todd, Ahh, gotcha, yeah that makes sense. ... read »
Nov 20, 2009 at 5:17 PM
Maintaining ColdFusion Sessions Across SMS Text Message Requests Without Cookies
Ben, sorry if I didn't make this clear. You can make it work like that if you want, just put <cfset session.foo = 1> (and <cfset application.foo = 1>) in your OnRequestStart() and it reve ... read »