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 »
5,406 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 »
5,406 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 »
5,406 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 »
5,406 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.


Post Comment  |  Ask Ben

Recent Blog Comments
Secret Admirer
Jul 4, 2009 at 12:23 PM
Project HUGE: Huge In A Hurry - Get Big - Phase 2 / Week 3
My Poor Dreamboat :( I feel so sad when I know you are hurting. I hope you feel better soon. ... read »
Jul 4, 2009 at 9:42 AM
FLV 404 Error On Windows 2003 Server
I bookmarked this page. Thanks for given this great post.... ... read »
Jul 4, 2009 at 4:00 AM
Terms Of Service / Privacy Policy Document Generator
thanks ben, I'm not a big fan of contracts so to find your no no-nesense ToS generator has helped me no end. all the best matt ... read »
Justice
Jul 3, 2009 at 11:10 PM
Create A Running Average Without Storing Individual Values
@Ben, I think you're going about this the wrong way. You're trying to use complicated techniques when there is a simple and beautiful technique readily available (a la Gary Funk's comment). Instead ... read »
Bob
Jul 3, 2009 at 9:19 PM
Project HUGE: Huge In A Hurry - Get Big - Phase 3 / Week 1
a good technical explanation http://crossfitphoenix.typepad.com/crossfit_phoenix_forging_/the-overhead-squat.html ... read »
Jul 3, 2009 at 9:03 PM
Create A Running Average Without Storing Individual Values
If I wanted to do this and only carry two numbers, I'd keep track of the sum and N. Then you are pretty much accurate all the time. average = (sum + new_number) / (N + 1) But all this was in a for ... read »
Roland Collins
Jul 3, 2009 at 8:58 PM
Create A Running Average Without Storing Individual Values
@Martin - not just floating point though. Depending on what langauge you're working in, decimals can cause just as many headaches if they're not precise enough. But again, for most applications, th ... read »
Isnogood
Jul 3, 2009 at 7:16 PM
Project HUGE: Huge In A Hurry - Get Big - Phase 3 / Week 1
Watch this http://www.nsca-lift.org/videos/default.shtml ... read »