• ...">

    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
    source share
    4 answers

    The each () method has an argument of "index". Use it to get the correct 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/

    +11
    source

    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
    source

    Use the index property provided by each function. Also, since this is text data, you can use the .text(...) function:

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

    See jsFiddle

    +1
    source
     var index = 0; $('#names-list li').each(function () { $(this).html(names[index]); index = index + 1; }); 
    -2
    source

    Source: https://habr.com/ru/post/1402642/


    All Articles