Given an HTML document containing some elements nested elements and the task is to count all the child elements of a particular element. It is very simple to count the number of child elements of a particular element using JavaScript. For example: If you have a parent element consisting of many child elements then you can use HTML DOM childElementCount property to count all the child elements of a particular element.
Syntax
node.childElementCount
Example:
<!DOCTYPE html> <html> <head> <title> How to count all child elements of a particular element using JavaScript? </title> </head> <body> <h1 style="color:green">GeeksforGeeks</h1> <h3> Click the button to count all<br> children the div element </h3> <h5>Count all child elements of <ul> elements</h5> <ul id="parentID"> <li>First element</li> <li>Second element</li> <li>Thrid element</li> <li>Fourth element</li> </ul> <button onclick="myGeeks()"> Click Here! </button> <h5 id="GFG"></h5> <script> // This fuction count the child elements function myGeeks() { var count = document.getElementById( "parentID").childElementCount; document.getElementById("GFG").innerHTML = "Total Number of Child node: " + count; } </script> </body> </html> |
Output:
- Before Clicking the Button:

- After Clicking the Button:

Recommended Posts:
- How to get the child element of a parent using JavaScript ?
- How to Check if an element is a child of a parent using JavaScript?
- How to count child element using jQuery ?
- Remove all the child elements of a DOM node in JavaScript
- How to remove parent element except its child element using jQuery ?
- Count elements whose sum with K is greater than max element
- How to select all children of an element except the last child using CSS?
- How to get the child node index in JavaScript?
- How to call a parent method from child class in JavaScript?
- How to select all child elements recursively using CSS?
- How to get specific number of child elements using CSS?
- How to iterate through child elements of a div using jQuery ?
- How to make container shrink-to-fit child elements as they wrap?
- How to disable mouseout events triggered by child elements?
- How to add a class to DOM element in JavaScript?
- How to change the ID of element using JavaScript ?
- How to set the value of a select box element using JavaScript?
- How to get the type of DOM element using JavaScript?
- How to check if an element has any children in JavaScript ?
- How to get the text without HTML element using JavaScript ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


