HTML DOM childElementCount Property


The HTML DOM childElementCount property is a read-only property that returns the number of child elements of a given element. The return type of the childElementCount is of unsigned long. It will only return the child element of the node on which it is queried and not all the child nodes of a HTML document.

Syntax

Following is the syntax for childElementCount property −

node.childElementCount

Example

Let us see an example for the HTML DOM childElementCount property −

<!DOCTYPE html>
<html>
<head>
<style>
   div {
      border: 2px solid blue;
      margin: 7px;
      padding-left:20px;
   }
</style>
</head>
<body>
<p>Click the button below to find out the no of children of the div element</p>
<button onclick="childCount()">COUNT</button>
<div id="myDIV">
<h3>HEADING</h3>
<p>First p element</p>
<p>Second p element</p>
</div>
<p id="Sample"></p>
<script>
   function childCount() {
      var x = document.getElementById("myDIV").childElementCount;
      document.getElementById("Sample").innerHTML = "The div element has "+x+" children";
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the COUNT button −

In the above example −

We have created a <div> element with id “myDIV” and three elements inside it. Two <p> elements and a <h3> header. We have also added colored border, margin and padding to the div to distinguish it from other elements −

div {
   border: 2px solid blue;
   margin: 7px;
   padding-left:20px;
}
<div id="myDIV">
<h3>HEADING</h3>
<p>First p element</p>
<p>Second p element</p>
</div>

We have then created a button COUNT which will execute the childCount() method on click.

<button onclick="childCount()">COUNT</button>

The childCount() method takes the element with id “myDIV”, which in our case is the <div>, element and assigns its childElementCount property value to variable x. Since we have two<p> elements and a <h3> element inside the <div>, so the childElementCount returned 3.

The value returned is then displayed in the paragraph with id “Sample” using the innerHTML() method on the paragraph −

function childCount() {
   var x = document.getElementById("myDIV").childElementCount;
   document.getElementById("Sample").innerHTML = "The div element has "+x+" children";
}

Updated on: 07-Aug-2019

47 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements