Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Basic
  • Last Updated : 17 Aug, 2020

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

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

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 function 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:



My Personal Notes arrow_drop_up
Recommended Articles
Page :