Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery append array value to each list item

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.

like image 568
Maverick Avatar asked Nov 28 '22 22:11

Maverick


1 Answers

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);
        }
    }
});
  1. I define the names list, the list element, and the list elements parent
  2. I detach the list from the dom so it doesn't refresh the dom for every list item added.
  3. I empty the list in case there are already values in there
  4. 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
  5. I run a loop going through each item in the array
  6. I append a list item with each name in the array to the detached #names-list
  7. 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
like image 73
Daniel Tonon Avatar answered Dec 04 '22 12:12

Daniel Tonon