aVC
aVC

Reputation: 2344

count li in ul after ul adds li from ajax

How can I count the number of li in a ul, after adding more li via ajax?

I tried $("#mylist li").size() but it does not count the newly added ones.

I know there is this option, $(returnedHTML).find('li').length but I want the total count of existing and newly added li

CODE: html

<ul id="mylist">
   <li> item 1</li>
   <li> item 2</li>
</ul>

jquery:

function updateNotificationCount(){    
    var nCount=$("#mylist li").length;      
        $("#Counter").html(nCount);     
    }

 $(document).ready(function(){
   $.ajax({
        type: "GET",
        url: "../scripts/getNotifications.php",
        data: "",

        success: function (data) {

              $('#mylist').append(data);
              updateNotificationCount();


        },
        error: function (xhr, ajaxOptions, thrownError) {alert("error");
            alert(xhr.statusText);
            alert(xhr.responseText);
            alert(xhr.status);
            alert(thrownError);
        }

        });
});

I can get teh ul updated without problem. only the counting is in limbo

Upvotes: 0

Views: 1336

Answers (2)

Rohit416
Rohit416

Reputation: 3486

you can try this,

$( "#mylist li" ).ajaxComplete(function(){
  var nCount=$("#mylist li").length;      
  $("#Counter").html(nCount);
});

your li are added dynamically to the DOM so can try when your ajax call complete. you did call the updateNotificationCount() on success but if that does not seems to work then you can use live() or delegate() to handle the dynamic count.

Upvotes: 0

Musa
Musa

Reputation: 97672

Just use $("#mylist li").length after you add the <li>s with ajax.

Upvotes: 2

Related Questions