What is the HTML childElementCount attribute?

Overview

In this shot, we will learn how to find the number of elements inside a parent element.

HTML DOM has a property that returns the number of child elements it has. We will use the childElementCount property to find the count of child nodes.

Console

Code explanation

  • In line 7, a button is given on the HTML page. Clicking on this button will call the change() function, which will print the number of child elements.

  • In lines 9-13, a div element that is a parent element for the 3 child paragraph elements is written with an ID of key.

  • In lines 15-20, we have written our JavaScript code inside the script tag, which has the change() function. This function uses the childElementCount property on the element we want. To check the child elements in the div, we use its ID with the getElementById("key") function. After the count is returned, we print it in the console.

Output

Click Run and then the try it button to check the console. We get the count 3, which is the total number of child elements inside div.

Free Resources