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);
}
}
});
- I define the names list, the list element, and the list elements parent
- I detach the list from the dom so it doesn't refresh the dom
for every list item added.
- I empty the list in case there are already values in there
- The each statement is more for triggering a function in relation to #names-list rather than handling multiple occurances of the list on the page
- I run a loop going through each item in the array
- I append a list item with each name in the array to the detached #names-list
- On the final loop, I add the full list back into the dom by appending it to the parent element
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