views:

274

answers:

3

This should be an easy one, but I'm not finding much online:

I have an unordered list <ul>, with a few list items underneath it <li>, and I'd like to address each one in the list, and act on it. How can I do this using jQuery?

Thanks.

+6  A: 

You could use each() for this.

E.g.

$('ul#id li').each(function(index, element) {
    var li = $(element);
    // ...
});
BalusC
I think you meant to link to the core `each()` - http://docs.jquery.com/Core/each as opposed to the utility function `each()` :)
Russ Cam
Yes, found that out a sec after :)
BalusC
I think you want only the immediate li children, as it may be nested. That means `$('ul#id > li').each(...)`
Randal Schwartz
+1  A: 

Something close to this:

$('#myulid').children('li').each(function(i, n) { alert($(this).html()); });
Josh Pearce
+1  A: 

Use this code and change id as appropriate.

$("ul#id_of_desired_ul > li").each(function() {
   //do stuff
   // $(this) references each li
});
Mercurybullet
I think you want only the immediate li children, as it may be nested. That means `$('ul#id > li').each(...)`
Randal Schwartz
Indeed, you are correct. Edited as appropriate.
Mercurybullet