In usability we trust

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!

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

About me

My name is Gabriel Svennerberg and I'm an usability oriented web developer living in Sweden.

This is my blog and it's all about web development and usability.

More about me

Blogroll

Copyright © 2007-2008
Gabriel Svennerberg