Open In App

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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: 

html




<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>Third element</li>
    <li>Fourth element</li>
</ul>
  
<button onclick="myGeeks()">
    Click Here!
</button>
  
<h5 id="GFG"></h5>
  
<script>
    // This function count the child elements
    function myGeeks() {
        var count = document.getElementById(
            "parentID").childElementCount;
      
        document.getElementById("GFG").innerHTML
            = "Total Number of Child node: "
            + count;
    }
</script>


Output:

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

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


Last Updated : 15 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads