342
votes

<div id="selected">
  <ul>
    <li>29</li>
    <li>16</li>
    <li>5</li>
    <li>8</li>
    <li>10</li>
    <li>7</li>
  </ul>
</div>

I want to count the total number of <li> elements in <div id="selected"></div>. How is that possible using jQuery's .children([selector])?

8
In pure JS, @Mo.'s answer is kind of low still, but use element.childelementCount - Charles L.

8 Answers

639
votes

You can use .length with just a descendant selector, like this:

var count = $("#selected li").length;

If you have to use .children(), then it's like this:

var count = $("#selected ul").children().length;

You can test both versions here.

33
votes
$("#selected > ul > li").size()

or:

$("#selected > ul > li").length
18
votes

fastest one:

$("div#selected ul li").length
15
votes
var length = $('#selected ul').children('li').length
// or the same:
var length = $('#selected ul > li').length

You probably could also omit li in the children's selector.

See .length.

13
votes

You can use JavaScript (don't need jQuery)

document.querySelectorAll('#selected li').length;
12
votes
$('#selected ul').children().length;

or even better

 $('#selected li').length;
4
votes

It is simply possible with childElementCount in pure javascript

var countItems = document.getElementsByTagName("ul")[0].childElementCount;
console.log(countItems);
<div id="selected">
  <ul>
    <li>29</li>
    <li>16</li>
    <li>5</li>
    <li>8</li>
    <li>10</li>
    <li>7</li>
  </ul>
</div>
2
votes

pure js

selected.children[0].children.length;

let num = selected.children[0].children.length;

console.log(num);
<div id="selected">
  <ul>
    <li>29</li>
    <li>16</li>
    <li>5</li>
    <li>8</li>
    <li>10</li>
    <li>7</li>
  </ul>
</div>