0

Having an issue with a for loop in jQuery only running once. Users is a array containing 4 items, and for each, it should append that item as a list element to userList, which is a ul. It appends the first element in the array as expected, but only that one. Not sure why it isn't running through the entire array?

$(document).ready(function() {
    var $currentUser = $('<li class="user"></li>');
    for(var i = 0; i < users.length; i++) {
        $currentUser.text(users[i]);
        $currentUser.appendTo('.userList');
    }    
    //alert(users.length) returns "4".
});
1
  • 4
    You don't create one <li> per user, you create one and overwrite its contents every iteration. Commented Apr 8, 2015 at 1:17

5 Answers 5

5

Try this

$(document).ready(function(){
for(var i = 0; i < users.length; i++) {
    var $currentUser = $('<li class="user"></li>');
    $currentUser.text(users[i]);
    $currentUser.appendTo('.userList');
  }
});

You're overwriting the element, instead of creating a new one for each user. Try the code above.

Sign up to request clarification or add additional context in comments.

Comments

3

More jQuery'ish

$('.userList').append(function() {
    return $.map(users, function(user) { 
        return $('<li />', {
            'class' : 'user',
            text    : user
        })
    });
});

FIDDLE

4 Comments

use this one instead of your code or all others, it is ugly, closely couples your initial design decisions with code and makes it harder to maintain to write dom elements as strings, use .map as adeneo did above. kudos.
just found that class does not have to be within quotation marks, and <li> also works
@erkaner - that works, but class is a reserved keyword in javascript and should not be used as a variable name or key, that's why it's quoted.
that is why I shared actually, to learn something from you :)
1

You aren't adding a new <li> for each iteration:

Here's a working solution:

for (var i = 0; i < users.length; i++) {
    $('<li class="user"></li>'
        .text(users[i])
        .appendTo('.userList');
}

https://jsfiddle.net/2abqa5us/1/

Comments

0

You create the li on the outside of the loop, then try to set the text of the same element to each user so you will overwrite it every iteration. Are you sure the last entry is not the one you see?

Comments

0

.text will overwrite previous text which looks like you got one users only

try this.

$(document).ready(function(){

    for(var i = 0; i < users.length; i++) {
        var $currentUser = $('<li class="user"></li>');
        $currentUser.text(users[i]);
        $currentUser.appendTo('.userList');
    }


});

1 Comment

OP tries to create N <li> elements, your code still creates one.

Your Answer

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