Uzair Khan
Uzair Khan

Reputation: 2970

Get number of <li> in any <ul> using javascript

I have a code in which I need to find the number of li tags, not the nested ones.

<ul class="ulStart">
   <li>
      <ul class="ulNested">
         <li></li>
         <li></li>
      </ul>
  </li>
  <li></li>
</ul>

Doing

document.querySelector('.ulStart').getElementsByTagName('li')

Gives me 4 <li>, which is not what I want, I want the number of li tags present in ulStart. Let me know if there is any way to do so. No jQuery, pure javascript.

Upvotes: 1

Views: 981

Answers (3)

Maysam Mok
Maysam Mok

Reputation: 369

<ul class="ulStart">
   <li>
      <ul class="ulNested">
         <li></li>
         <li></li>
      </ul>
  </li>
  <li></li>
</ul>

Try use the following query selector:

console.log(document.querySelectorAll('.ulStart > li').length);

Results in:

HTMLCollection(2) [li, li]

Upvotes: 1

Artyom Amiryan
Artyom Amiryan

Reputation: 2966

console.log(document.querySelectorAll('.ulStart > li').length);
<ul class="ulStart">
   <li>
      <ul class="ulNested">
         <li></li>
         <li></li>
      </ul>
  </li>
  <li></li>
</ul>

Upvotes: 2

Aurel B&#237;l&#253;
Aurel B&#237;l&#253;

Reputation: 7963

let count = document.querySelectorAll("ul.ulStart > li").length;
console.log(count);
<ul class="ulStart">
  <li>
    <ul class="ulNested">
      <li></li>
      <li></li>
    </ul>
  </li>
  <li></li>
</ul>

Use the > (direct child) CSS selector. See MDN - Child selectors.

Upvotes: 5

Related Questions