gautamlakum
gautamlakum

Reputation: 12035

jQuery count child elements

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

Upvotes: 377

Views: 524655

Answers (8)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92717

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>

Upvotes: 3

Mo.
Mo.

Reputation: 27503

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>

Upvotes: 5

Đặng Văn Thanh
Đặng Văn Thanh

Reputation: 558

You can use JavaScript (don't need jQuery)

document.querySelectorAll('#selected li').length;

Upvotes: 16

bcosca
bcosca

Reputation: 17555

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

or:

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

Upvotes: 38

Ali Tarhini
Ali Tarhini

Reputation: 5358

fastest one:

$("div#selected ul li").length

Upvotes: 18

Martin Algesten
Martin Algesten

Reputation: 13620

$('#selected ul').children().length;

or even better

 $('#selected li').length;

Upvotes: 12

Nick Craver
Nick Craver

Reputation: 630627

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.

Upvotes: 685

Felix Kling
Felix Kling

Reputation: 817128

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.

Upvotes: 16

Related Questions