Abhijit Borkakoty Abhijit Borkakoty - 5 months ago 8
jQuery Question

Append a list item through loop in jQuery

How do I append a new list item through loop in JQuery. Every time the user clicks the button, a new item gets appended showing the correct index.

Here a sample of my code:

$('#append').click(function() {
$('ul#myList > li').each(function(i) {
var content = "<li>" + "Item" + (1+i) + "</li>";
$(this).append(content);
});
});


Output should be like

Item 1
Item 2
Item 3
and so on

Answer

Find the total length and assign that value to the variable then use this code

 $('#append').click(function() {
          var contentLength = $('ul#myList > li').length;
          var content = "<li>" + "Item" + (contentLength+1) + "</li>";
          $('ul#myList').append(content);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="append">Add More</button>

<ul id="myList">
  <li>Item1</li>
</ul>

Comments