Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 799
gautamlakum Avatar asked Nov 27 '10 10:11

gautamlakum


People also ask

How to count child elements in jQuery?

Count child elements using jQuery. JavaScript Code: var count = $("#selected p"). length; console.

How do you count children's elements?

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.

How do I count the number of elements in jQuery?

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.

How do you check if a div has a child or not?

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 .


2 Answers

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.

like image 53
Nick Craver Avatar answered Sep 22 '22 04:09

Nick Craver


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

or:

$("#selected > ul > li").length 
like image 27
bcosca Avatar answered Sep 25 '22 04:09

bcosca