<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])
?
Count child elements using jQuery. JavaScript Code: var count = $("#selected p"). length; console.
To get the count or number of child elements of a specific HTML Element using JavaScript, get reference to this HTML element, and read the childElementCount property of this HTML Element. childElementCount property returns the number of child elements in this HTML Element.
To count all HTML elements, we use length property. The length property is used to count number of the elements of the jQuery object. where selector is the object whose length is to be calculated.
To check if an HTML element has child nodes, you can use the hasChildNodes() method. This method returns true if the specified node has any child nodes, otherwise false .
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.
$("#selected > ul > li").size()
or:
$("#selected > ul > li").length
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With