I have an unordered list like this:
<ul id="names-list">
 <li></li>
 <li></li>
 <li></li>
 <li></li>
</ul>
Lets say I want to add a name from this list to each of the <li> items:
var names = [ "Jon", "Nick", "Bill", "Tom" ];
And my code is like this:
$('#names-list li').each(function () {
 $(this).append(names);
});
But from some reason it doesn't work. Can someone tell me what am I doing wrong? Thanks.
Why has no one pointed out that basing the number of li's on the number of empty li's in the dom is a horrible way to do it? It's much better to generate the li's based on how many items there are in the array.
Try this instead:
HTML
<div id="parent">
    <ul id="names-list">
        <!-- empty list -->
    </ul>
</div>
JS
var names = [ "Jon", "Nick", "Bill", "Tom" ];
var list = $("#names-list");
var parent = list.parent();
list.detach().empty().each(function(i){
    for (var x = 0; x < names.length; x++){
        $(this).append('<li>' + names[x] + '</li>');
        if (x == names.length - 1){
            $(this).appendTo(parent);
        }
    }
});
Update: Pure JS, modern syntax version
If you are able to use modern code then this is a pure JS es6 version that I would use today:
const names = [ "Jon", "Nick", "Bill", "Tom" ];
const listElem = document.querySelector("#names-list");
// Creates a string of HTML to inject rather than appending DOM elements
const listItemsHtml = names.map(name => `<li>${name}</li>`).join('');
// Replaces the current content in the list with the new content
listElem.innerHTML = listItemsHtml
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With