Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the number of children?

Tags:

jquery

People also ask

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.


You can use .length, like this:

var count = $("ul li").length;

.length tells how many matches the selector found, so this counts how many <li> under <ul> elements you have...if there are sub-children, use "ul > li" instead to get only direct children. If you have other <ul> elements in your page, just change the selector to match only his one, for example if it has an ID you'd use "#myListID > li".

In other situations where you don't know the child type, you can use the * (wildcard) selector, or .children(), like this:

var count = $(".parentSelector > *").length;

or:

var count = $(".parentSelector").children().length;

You don't need jQuery for this. You can use JavaScript's .childNodes.length.

Just make sure to subtract 1 if you don't want to include the default text node (which is empty by default). Thus, you'd use the following:

var count = elem.childNodes.length - 1;

Try to get using:

var count = $("ul > li").size();
alert(count);

You can use Element.childElementCount

ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/childElementCount


let count = ThatParentElement.childElementCount;