The way to count depends a lot on what you mean by "li’s inside a div".
In your specific case, just do document.querySelectorAll('#collapse305 li').length
, as your own answer indicated.
But what if we have an HTML like this:
<div id="collapse305">
<div class="panel-body">
<ul id="lista1">
<li>Test1</li>
<li>Test2</li>
<li>Test3</li>
<li>
Test4
<ul id="sublista1">
<li>Subtest4.1</li>
<li>Subtest4.2</li>
</ul>
</li>
</ul>
<p>blablabla</p>
<ul id="lista2">
<li>Test5</li>
<li>Test6</li>
</ul>
<div id="outra">
<ul id="lista3">
<li>Test7</li>
<li>Test8</li>
<li>
Test9
<ul id="sublista3">
<li>Test10</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
You want to count all the elements li
? Or only those of the first ul
? Or just the ones who aren’t nesting? Or just the ones on the first level?
For example, if I do document.querySelectorAll('#collapse305 > div > ul > li')
, he’ll just take Test1
, Test2
, Test3
, Test4
, Test5
and Test6
, since the >
only takes elements that are direct descendants, that is to say, #collapse305 > div
only takes the div
who is the immediate daughter of the person whose id
is collapse305
(which in this case is the div class="panel-body"
), afterward > ul
only takes the elements ul
who are the direct children of this div class="panel-body"
(that is, only the elements ul
whose id’s are lista1
and lista2
), and finally > li
will take only the elements li
who are their direct children ul
's (so he doesn’t take the Subtest4.1
and neither Subtest4.2
, since these are not direct children of lista1
).
When you don’t use >
, he picks up the descendants of that element, regardless of whether they are direct children (i.e., they may be "grandchildren", "great-grandchildren", etc). See more about these selectors here.
This allows several different ways to count. For example, if you remove one >
selector: document.querySelectorAll('#collapse305 div > ul > li')
.
Now he’ll get any div
inside collapse305
, which means that beyond the div class="panel-body"
, will also be caught the div id="outra"
, and with it the ul id="lista3"
will also be considered. However, only the li
'who are his direct children ul
, and therefore the Test10
is out. The result will be Test1
, Test2
, Test3
, Test4
, Test5
, Test6
, Test7
, Test8
and Test9
.
But if I change to document.querySelectorAll('#collapse305 > div > ul li')
, now I get all the li
's within lista1
and lista2
, that is to say, Test1
, Test2
, Test3
, Test4
, Subtest4.1
, Subtest4.2
, Test5
and Test6
.
Of course for simpler cases like yours (within the div
there is only one ul
without li
's nested), it will not make a difference. But depending on how HTML is and what you want to consider in the count, using the right selector can make all the difference.