beans
beans

Reputation: 1765

Loop through a list?

<ul id ="questions">
    <li class="question"></li>
    <li class="question"></li>
    <li class="question"></li>
</ul>

How can I iterate through each list element?

So far I have:

$("#questions li").each(function() { });

But no luck, any ideas?

I for got to mention that all but the first li is being added on the fly, is this why the loop is not picking them up?

Upvotes: 0

Views: 6067

Answers (4)

Sam Thornton
Sam Thornton

Reputation: 983

What are you trying to do as you iterate through each list item? Using the .each function should work great. If you're having a problem with it though it might be because you are calling the function too early, in which case the ready function (as @roXon mentioned) will fix that. Otherwise, if you're having issues. It might be because of the space you have between the id and = sign on your <ul>

Here's a jQuery example of iterating through each element:

$('#questions li').each(function() {
    var i = $(this).index() + 1;
    $(this).text("List item " + i);
});

Feel free to play around with it: http://codepen.io/sdthornton/pen/gkayG

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 206028

LIVE DEMO

Use .ready function, doing so the DOM modifications will take place once it's read.

$(function(){
   $("#questions li").each(function() {
          // DO SOMETHING
   });
});

http://api.jquery.com/ready/

Or use your fireBug or devTool to get any other possible errors.

Upvotes: 1

Ryan Spears
Ryan Spears

Reputation: 3011

It would seem that you are iterating through each list item.

If you change the dom elements to:

<ul id ="questions">
    <li class="question">one</li>
    <li class="question">two</li>
    <li class="question">three</li> 
</ul>

and then use the following jQuery code when the document loads:

$(function(){
   $("#questions li").each(function() {
          alert($(this).html()); //Or whatever you want to do with that item
   });
});

You should be outputting:

  • one
  • two
  • three

Note: you can test your JavaScript and jQuery at http://jsfiddle.net/

Upvotes: 0

eivers88
eivers88

Reputation: 6247

Use the function parameters to get the index and value of each list item:

$("#questions li").each(function(index, value) {
    console.log(index + '' + $(value).html());
});

Upvotes: 0

Related Questions