Reputation: 1246
I have a list of LI in a UL, they are all dynamically added via jQuery. I am trying to alert the number of LI in this list. Right now I can only get it to alert 0. I think it is because its trying to count the original number on load? here is my code and fiddle:
https://jsfiddle.net/ts7Lwbfs/1
<ul id="list">
<li>original</li>
</ul>
var familly = []
familly.push('<li>1</li>');
familly.push('<li>2</li>');
familly.push('<li>3</li>');
familly.push('<li>4</li>');
$('#list').prepend(familly);
$('#list').on('click', 'li', function(ev){
var howMany = $('#list').length;
alert(howMany);
});
How can I get it to alert the total number of LI after they are dynamically added?
Upvotes: 0
Views: 6468
Reputation: 8591
You can count the total number of list items this way:
$('#list').on('click', function(){
var howMany = $('#list li').length;
alert(howMany);
});
To get the number of added list items, first capture the count of original list items before you add new ones, and then subtract the total in your function from the original count.
var originalCnt = $('#list li').length;
$('#list').prepend(familly);
$('#list').on('click', function(){
var howMany = $('#list li').length - originalCnt;
alert(howMany);
});
Upvotes: 1
Reputation: 8858
If you are trying to find only the count of newly added li ( excluding the original ) , you can filter the li and exclude the first one using :not:first
expression.
$('#list').on('click', function(ev){
var howMany = $(this).find('li:not(:first)').length;
alert(howMany);
});
https://jsfiddle.net/DinoMyte/ts7Lwbfs/4/
Upvotes: 1
Reputation: 318182
The selector $('#bet_slip')
matches an element with the ID bet_slip
, and as ID's are unique jQuery doesn't expect there to be more than one, and as none of your elements have that ID, you get zero?
Seems like what you want is to count the number of LI's in the #list
list
$('#list').on('click', 'li', function(ev){
var howMany = $('#list li').length;
alert(howMany);
});
Note that this counts all LI's currently present, including the one that was there originally.
Upvotes: 2