Looping with jQuery

I’ve started working with the Javascript framework jQuery lately and I must say that I find it very enjoyable! I have previously mostly used Prototype and DOMAssistant, and although they excel in some areas I somehow find jQuery more fun to code with.

Here’s a simple tip on how to loop through elements with jQuery that I thought I’d share.

An example

We start with a simple unordered list.

<ul id="my_list">
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>

What we want to do now is to change the color of each list item to red. With regular DOM scripting this would probably take a few lines of code but with jQuery we need just one.

$('#my_list li').css('color', 'red');

This would result in:

  • Item
  • Item
  • Item

If you want to do something a little more fancy, like something different with each item, you have to write a little more code, but not much. First you have to grab the the list elements like in the previous example by using selectors. By using the each() method, you are then able to loop through each item. By assigning an anonymous function to each() you get access to every individual item by using $(this).

Notice that in the anonymous function there’s an attribute i. That’s the number of each item, just like in any normal array, starting from 0 and incrementing.

$('#my_list li').each(function(i) {
$(this).append(i.toString());
});

The result is a list with the item number attached to the text inside the elements like this:

  • Item0
  • Item1
  • Item2

The really cool thing about this is that each iteration has it’s own function scoop. If you ever tried to do this with regular DOM scripting and a standard for loop you’ve most likely ran into some kind of scoop problem when dynamically assigning values to an object. They all end up getting the same value. jQuery elegantly solves this and makes you’re coding life a little bit easier.

Pretty cool don’t you think? Happy coding!

About the author

Gabriel Svennerberg is an UX Designer and FrontEnd Developer living in Sweden. When he's not busy designing or building applications at Meetod, he writes about UX Design and all things web on In usability we trust. Gabriel is the author of the book Beginning Google Maps API 3 published by Apress. Gabriel on Google+
  • http://www.twitter.com/roprice Ro

    Thanks for the article… helped me do this:

    ————————————-
    $(‘#my_list li’).each(function()
    {
    $(this).mouseover(function()
    {
    $(‘#my_list li’).removeClass(“selected”);

    $(this).addClass(“selected”);
    })
    })
    ———————————–

    Can you think of anyway to shorten this?

    Thanks

  • http://www.svennerberg.com Gabriel Svennerberg

    I think that there’s a fundamental flaw in your code. Surely you want the class to be appended only when the mouse hovers over it? In that case you could write it like this, but it’s actually longer than your code :-)

    $('#my_list li').each(function() {
        $(this).hover(function() {
            $(this).addClass('selected');    
        },
        function() {
          $(this).removeClass('selected');  
        });
    });
    

    But on the other hand it’s better to achieve this with pure CSS. Then it gets really short.

    #my_list li:hover {
        /* Whatever style you want it to have */
    }
    
  • Michel Moos

    Thank you for this!! (I knew there was an elegant solution.)

  • http://notupyet Michel Moos

    ps: My implementation:

    var apptDetails='undefined';
    function get_selected_values() {
      jQuery(document).ready(function($) {
        apptDetails='' + "n";
        $("select").each(function(i){
          var v=$(this).val();
          if (v != 'none selected') {
            apptDetails = apptDetails + v + "n";
          }; 
        });  
      });
    }
    
  • http://www.svennerberg.com Gabriel Svennerberg

    Michel: There’s almost always an elegant solution in jQuery! Got to love it! One thing to be aware of though is that if performance is an issue, you are better of with regular for-loops.

  • santosh

    $(‘#my_list li’).each(function(i) {
    $(this).append(i.toString());
    });

    * Item0
    * Item1
    * Item2

    Instead i want to get
    * Item1
    * Item2
    * Item3

    How to achieve the same???

  • http://www.svennerberg.com Gabriel Svennerberg

    Santosh: It’s easy, you just add 1 to i each iteration.

    $('#my_list li').each(function(i) {
      $(this).append(i + 1);
    });
    
  • http://twitter.com/jamiegrinnell Jamie Grinnell

    Can I use this to loop through a bulleted list in which I want to hide 2 of the dynamic results? The bulleted list is based on an ID and a Question. One Question has 4 answers, one question uses the same answers, but I only need 2 of the 4 responses to be shown. Is this possible?