jQuery Minute™

…a jQuery Minute™ later and you're done!



jQuery Iteration and each()

without comments

There was a recent thread on the jQuery discussion group in that there was a need for looping through a series of elements and dynamically binding an event. An issue was brought up with closures and the arguments for dynamic binding of functions. Brandon Aaron provided an elegant solution that makes use of jQuery’s internal each() function. Let’s jump in!

So here’s a paraphrase of Brandon’s code:

Example 1:
jQuery.each( [0,1,2,3,4], function(index, item){
// Your code
});

At first glance this may look the same as your standard iteration code using each but it differs slightly and that is where the benefit is. Let’s look at using the standard each method on a jQuery object:

Example 2:
$(‘selector’).each(function(index){
// Your code
});

In this example jQuery internally manages the collection (array) of matched elements by the selector.

But, by using jQuery’s internal .each() method (Example 1) we’re able to pass in an arbitrary array in which each item will have the callback executed. An elegant solution to your typical for ( i ) loop. Your callback can accept two arguments: index, item where index is the numerical zero based index in the array of the current item and item is the value of the current array. Also worth noting is that by returning false from you callback you can stop iteration over the array (this is the same as using a break; statement in a for loop).

Happy coding!

Written by jdsharp

February 7th, 2008 at 8:00 am

Leave a Reply