Reputation: 103
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>
Upvotes: 0
Views: 83
Reputation: 115222
Use :nth-child()
and jQuery.each()
var levels = ["1", "2", "3", "4"];
$.each(levels, function(i, x) {
$('ul li:nth-child(' + (i + 1) + ')').html(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>
Upvotes: 0