Lukas Lukas - 6 months ago 15
Javascript Question

Append an array to each list item in separate ul's

I am trying to add the contents of an array to every list on the page by appending 1 through 4 to the list items. The problem I'm having is that I can't do this to every list, and if their is only 3 list items, I don't want to add another item, just end the list at 3. I'd also like to remove the 0s.

Thanks in advance!



var levels = [ "1", "2", "3", "4" ];
$('ul li').each(function (x) {
$(this).append(levels[x]);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul>
<li>0</li>
<li>0</li>
<li>0</li>
<li>0</li>
</ul>

<ul>
<li>0</li>
<li>0</li>
<li>0</li>
</ul>

<ul>
<li>0</li>
<li>0</li>
<li>0</li>
<li>0</li>
</ul>





FIDDLE

Answer

Iterate over the lists first, and then iterate over the list items for each list

var levels = [ "1", "2", "3", "4" ];

$('ul').each(function(i, ul) {
    $(ul).find('li').each(function(j, li) {
        $(this).html(levels[j]);
    });
});

FIDDLE