jQuery count child elements

JavascriptJqueryDom

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

or:

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

Solution 3 - Javascript

fastest one:

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

Solution 4 - Javascript

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.

Solution 5 - Javascript

You can use JavaScript (don't need jQuery)

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

Solution 6 - Javascript

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

or even better

 $('#selected li').length;

Solution 7 - Javascript

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>

Solution 8 - Javascript

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongautamlakumView Question on Stackoverflow
Solution 1 - JavascriptNick CraverView Answer on Stackoverflow
Solution 2 - JavascriptbcoscaView Answer on Stackoverflow
Solution 3 - JavascriptAli TarhiniView Answer on Stackoverflow
Solution 4 - JavascriptFelix KlingView Answer on Stackoverflow
Solution 5 - JavascriptĐặng Văn ThanhView Answer on Stackoverflow
Solution 6 - JavascriptMartin AlgestenView Answer on Stackoverflow
Solution 7 - JavascriptMo.View Answer on Stackoverflow
Solution 8 - JavascriptKamil KiełczewskiView Answer on Stackoverflow