Using jQuery, how do I go through each nested ul.item, count the number of LI, and return that size/length in a parent span.someClass on that page?
<ul>
<li><span class="someClass">3</span>
<ul class="item" style="display:none">
<li>count me</li>
<li>count me</li>
<li>count me</li>
</ul>
</li>
<li><span class="someClass">1</span>
<ul class="item" style="display:none">
<li>count me</li>
</ul>
</li>
<li><span class="someClass">2</span>
<ul class="item" style="display:none">
<li>count me</li>
<li>count me</li>
</ul>
</li>
</ul>
JavaScript Code :$("button"). click(function(){ console. log($("li"). length); });
To count all HTML elements, we use length property. The length property is used to count number of the elements of the jQuery object.
In JavaScript, you can use the . getElementsByTagName() method to get all the <li> elements in <ul>. In-addition, you can use the . querySelectorAll() method also to get all the <li>.
$("ul.item").each(function() {
// reusabilty
var context = $(this);
// count and populate
context.prev(".someClass").text(context.children().length);
});
Omit .someClass
in prev()
call if these span
elements are always immediately before your ul
elements. In that case filtering in prev
is not necessary and superfluous.
Try this,
Live Demo
$('.someClass').each(function(){
$(this).text($(this).next('ul').find('li').length);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With