Master the jQuery for each loop

The jQuery for each loop can be very powerful. It is used just like any other jQuery function such as .click(), .hover(), etc. and it accepts a callback. As you know, or have probably guessed, the jQuery for each function loops over selected items and does whatever you’d like to targetted items.

You may be asking yourself:

But isn’t that what CSS or jQuery selectors do anyway? What’s the difference?

Standard jQuery for .each()

Not only does the jQuery for each function loop over each selected element, it also keeps track of the element index within the loop. For example:

As you can see in the example, it’s some very basic HTML with some very basic CSS. The jQuery is also relatively simple, I’m pretty sure you would be able to guess what is going on even if I didn’t explain, but I will!

The above example is selecting all <li> elements and looping over them. It is then adding a class of ‘item-’ with its index value appended to it. The index begins at 0.

The $(this) keyword references each iterated element. This is where .each() becomes very useful.

I feel that’s a pretty straight forward jQuery for each loop that you should be able to get the hang of pretty quickly if you’re fairly familiar with jQuery.

The javascript for loop

If you’re still pretty new to jQuery and you’re feeling adventurous, how about throwing in a javascript for loop instead of a jQuery for each loop? ‘Why’ you ask? Well because it is much faster.

While you won’t notice the difference on small scripts and pages, it could make a difference while looping through many items and even other loops. It’s also never a bad thing to learn some javascsript when you can.

Personally I prefer doing this. It certainly isn’t much more complicated than the jQuery version.

Alright, how is $.each() any different?

If you didn’t already know, there is another jQuery for each function, but it’s not the same as the one we’ve already covered. The $.each() function loops over items in an array or items in an object. I didn’t run into arrays or objects until quite a while after I was comfortable with jQuery, so don’t feel left out if you don’t know what’s going on. I suggest having a look at the jQuery fundamentals page. It covers basic javascript and helps you use jQuery to it’s full potential.

Back to the point: how would we use $.each()? Without further ado, here’s an example!

In this example I’ve used an object instead of an array, but they both work pretty much the same way. First the object obj is declared with a couple of random key and value values. It is then looped over using the jQuery function. As an example, I’ve appended the values to a div and also used the key as the class of each paragraph.

Conclusion

As you can see, there isn’t much to jQuery or javascript for each loops! Save time and make your life more simple by making use of them!

What say you?

  1. Hervé says:

    Hello Jamy,
    I need to loop inside an array of color names to change a div background color at a regular pace and in an infinite loop.

    I have trying with each and setInterval.
    I use jquery 1.6.4

    $(document).ready(function()
    {
        var cols = ["red", "green", "yellow", "blue", "purple"];
        jQuery.each(cols, function changi(i) {
          setInterval(function() {
          $('#menu').append('fifi '+cols[i]+' ');  // as a witness of the behaviour
          $('#menu').css({'background-color' : cols[i]});
    }, 5000);
        });    
    });

    I can not get the effect. background colors are thrown all at the same time. I can not set time intervals between each loop?

    1. Jamy Golden says:

      I think the problem is because that for each is firing a setInterval() for each item in the array at the same time instead of looping through them. You could do something like this:

      var num = 0;
      var cols = [];
      
      cols = ["red", "green", "yellow", "blue", "purple"];
      
      setInterval(function() {
      
            $('#menu').append('fifi '+cols[num]+' ');  // as a witness of the behaviour
            $('#menu').css({'background-color' : cols[num]});
            num += 1;
      
      }, 5000);
  2. Golak Jena says:

    Its really needful……..

    Thanks

  3. Furqan says:

    Thank you. exactly what i am looking for :)

  4. Christian says:

    “ado” not “a due”

    1. Jamy Golden says:

      lol thanks for that

  5. Martins says:

    Hi!

    I have a problem here. Assume that:

    AAA
    BBB
    CCC

    Im trying to fadeIn, fadeOut each of these paragraphs one by one (not all of them simultaneously). Other goal is to repeat this function after it has finished. Ive written a script that does the job but it feels a bit messy (excludes setInterval method that was used for repeating the function). Could you please give me a hint! :)

    My code:

    $(document).ready(function() {
    	for (var i = 0; i<3; i++)
    	{ 
    		$(".slept").eq(i).delay(8000).fadeIn(300).delay(8000-2*300-200).fadeOut(300);
    	};
    });
  6. Thomas says:

    Very Important article, thanks. Especially the eq() function ; )

  7. Nas says:

    how do you specify a condition each loop , eg:

    for( i = 0; i <= 10; i++ ) where the i <= 10 is the condition

    1. Jamy Golden says:

      I don’t quite understand. I could help if you elaborate a bit more.

    2. Nas says:

      in a loop you usually have an iteration and a condition:

      so a while loop has a condition:

      while ( condition )

      for loop:

      for ( i=0; condition; i++ )

      can you specify a condition for the $.each loop.

    3. linyuan says:

      actually $.each already set a condition which is from beginning (0) to last (object.length) this is condition, of course if you want to set other condition, for example: var list=$(#ulid .liclass);
      in list you get 10 li. and then you need only need to do sth for first 5 li, you can add condition in $.each(list,function(i){ $(this).(do sth);
      if(i>5){ return false;} }) and this condition could be whatever you need,you can also set if($(this).is(‘#stop’)){return false;}

  8. Lisa Walker says:

    Well, I did further research on this (excuse me for not have a ton of jquery experience), and I found that my setup for the second list was not accurate.
    So the main issue is resolved of pairing the value with the text.
    However, now at the end it is adding an extra option with no value and undefined text.
    Geeze, one of these days!

  9. Lisa Walker says:

    Ok, I determined that it was something to do with the setup again of the list. Here we sort of share portions of code and another coder gave me his setup for the list and apparantly the last item had a floating , at the end of the line, which when the split occurred it saw this as another line with undefined text in the second list.

    SOOO HAPPY I figured this out.

    1. Jamy Golden says:

      Well done! :)