Reputation: 2970
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
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
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
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