JQuery append array value to each list item

31,621

Solution 1

The each() method has an "index" argument. Use it to get the proper value in your list.

var names = [ "Jon", "Nick", "Bill", "Tom" ];
$('#names-list li').each(function (index) {
    $(this).text(names[index]);
});

​ Demo: http://jsfiddle.net/7ESKh/

Solution 2

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

Solution 3

Use the index property provided to the each function. Also, since it's text data you could use the .text(...) function:

$('#names-list li').each(function (index) {
  $(this).text(names[index]);
});

See jsFiddle

Share:
31,621
Maverick
Author by

Maverick

Updated on August 01, 2021

Comments

  • Maverick
    Maverick almost 3 years

    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.