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.
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
divelement that is a parent element for the 3 child paragraph elements is written with an ID ofkey. -
In lines 15-20, we have written our JavaScript code inside the
scripttag, which has thechange()function. This function uses thechildElementCountproperty on the element we want. To check the child elements in thediv, we use its ID with thegetElementById("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.