JQuery appends an array value to each list item
I have an unordered list:
<ul id="names-list"> <li></li> <li></li> <li></li> <li></li> </ul> Suppose I want to add a name from this list to each of the <li> elements:
var names = [ "Jon", "Nick", "Bill", "Tom" ]; And my code looks like this:
$('#names-list li').each(function () { $(this).append(names); }); But for some reason this will not work. Can someone tell me what I am doing wrong? Thanks.
+4
4 answers
Why has no one pointed out that basing the number li on the number of empty li in dom is a terrible way to do this? It is much better to create li based on the number of elements 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 a list of names, a list item, and a list item's parent
- I disconnect the list from dom so that it does not update dom for each added list item.
- I empty the list if it already has values
- Each statement is more suitable for launching a function with respect to # names-list, rather than for processing several list events on a page
- I run a loop going through each element of the array
- I add a list item with each name in the array to a separate file # names-list
- In the last loop, I add the complete list back to dom, adding it to the parent
+11