Abhijit Borkakoty Abhijit Borkakoty - 1 year ago 45
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>";

Output should be like

Item 1
Item 2
Item 3
and so on

Answer Source

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>";
<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">