简体   繁体   中英

How to count the number of list items that are dynamically added to a page using jQuery?

I am trying to count the number of list items on a page which are added dynamically using jQuery. I know how to count them when they are already on the page. But, how do I do it when list items are being added dynamically?

HTML:

<ul>
  <li class="working">Lorem 1</li>
  <li class="working">Lorem 2</li>
  <li class="working">Lorem 3</li>
  <li class="working">Lorem 4</li>
  <li class="working">Lorem 5</li>
</ul>

jQuery:

$(document).ready(function(){
    if($('li.working').length > 2) {
        alert('More than 2');
    }
});

Here's a Fiddle that counts static number of list items. Can somebody please help me count the number of list items when they are added dynamically on the page?

Use the below HTML :

<button>Click to add li</button>
<p>No. of list items : <span></span></p>
<ul></ul>

And Below is the jquery code to add list-items dynamically and display the list-items count value :

$(document).ready(function(){
  var c=1;
  $('button').click(function(){
    $('ul').append("<li class='working'>Lorem "+c+"</li>");
    c++;
    $('p span').text($('li.working').length);
  });
});

So, you want to know the length after you add the list dynamically via jquery. You can just count the length after the successful append of list. I have created a dummy append with button(you can do it however you prefer).
HTML:

<ul>
  <li class="working">Lorem 1</li>
  <li class="working">Lorem 2</li>
  <li class="working">Lorem 3</li>
  <li class="working">Lorem 4</li>
  <li class="working">Lorem 5</li>
</ul>
<input type="button" id="add" value="Add" />

JS:

$(document).ready(function(){


  $( "#add" ).on( "click", function() {
    var size = $('ul').find('li').length;
    $('ul').append('<li class="working">Lorem '+(size+1)+'</li>');

    //replica of the ajax dynamic addition. Just check for the length after successful append in you UI
    $( "ul" ).promise().done(function() {
   if($('li.working').length > 2) {
    alert($('li.working').length);
  }
  });
    });

});

Here is the FIDDLE: https://jsfiddle.net/rumba_alex47/1mmokwvf/

Please find the demo here .

HTML:

<ul>
    <li class="working">Lorem 1</li>
    <li class="working">Lorem 2</li>
    <li class="working">Lorem 3</li>
    <li class="working">Lorem 4</li>
    <li class="working">Lorem 5</li>
</ul>
<button onclick="add()">
    ADD
</button>

JS:

function add() {
    $('ul').append('<li class="working">Lorem ' + ($('ul li.working').length + 1) + '</li>');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM