Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - count li in each of multiple ul and return value

Tags:

html

jquery

dom

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>
like image 464
dissident Avatar asked Nov 21 '12 16:11

dissident


People also ask

How to count number of li in ul using jQuery?

JavaScript Code :$("button"). click(function(){ console. log($("li"). length); });

How do I count the number of elements in jQuery?

To count all HTML elements, we use length property. The length property is used to count number of the elements of the jQuery object.

How do you find the number of Li in UL?

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>.


2 Answers

$("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.

like image 61
Robert Koritnik Avatar answered Sep 24 '22 16:09

Robert Koritnik


Try this,

Live Demo

 $('.someClass').each(function(){    
     $(this).text($(this).next('ul').find('li').length);
 })​
like image 21
Adil Avatar answered Sep 24 '22 16:09

Adil