372

<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])?

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
gautamlakum
  • 11,815
  • 23
  • 67
  • 90

8 Answers8

670

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.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
38
$("#selected > ul > li").size()

or:

$("#selected > ul > li").length
bcosca
  • 17,371
  • 5
  • 40
  • 51
18

fastest one:

$("div#selected ul li").length
Ali Tarhini
  • 5,278
  • 6
  • 41
  • 66
  • 2
    This is not the fastest, in fact you slowed it down by adding `div` on there :) – Nick Craver Nov 27 '10 at 10:28
  • 1
    It really depends on which browser you use. In many modern browsers, adding the element uses findByElement before finding by id or class, which is slower. Soon this will be a moot point either way though, because all DOM searches will be done using one native function. In any case, a simple getElementById('selected') or $('#selected') would be faster at this point. – Alex K Dec 10 '12 at 19:45
16

You can use JavaScript (don't need jQuery)

document.querySelectorAll('#selected li').length;
16
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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
12
$('#selected ul').children().length;

or even better

 $('#selected li').length;
Martin Algesten
  • 13,052
  • 4
  • 54
  • 77
5

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>
Mo.
  • 26,306
  • 36
  • 159
  • 225
3

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>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345