realbadrabbits
realbadrabbits

Reputation: 103

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

Upvotes: 0

Views: 83

Answers (2)

Pranav C Balan
Pranav C Balan

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

adeneo
adeneo

Reputation: 318182

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

Upvotes: 1

Related Questions