4

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.

3 Answers 3

14

You could use each() for this.

E.g.

$('ul#id li').each(function(index, element) {
    var li = $(element);
    // ...
});
Sign up to request clarification or add additional context in comments.

3 Comments

I think you meant to link to the core each() - docs.jquery.com/Core/each as opposed to the utility function each() :)
Yes, found that out a sec after :)
I think you want only the immediate li children, as it may be nested. That means $('ul#id > li').each(...)
3

Something close to this:

$('#myulid').children('li').each(function(i, n) { alert($(this).html()); });

Comments

3

Use this code and change id as appropriate.

$("ul#id_of_desired_ul > li").each(function() {
   //do stuff
   // $(this) references each li
});

1 Comment

I think you want only the immediate li children, as it may be nested. That means $('ul#id > li').each(...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.