How to count all child elements of a particular element using JavaScript ?

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


Output:

  • Before Clicking the Button:
  • After Clicking the Button:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.