The childElementCount property returns the number of child elements an element has.
The following code finds out how many child elements a <div> element has:
var x = document.getElementById("myDIV").childElementCount;
Click the button to find out how many children the div element has.
<!DOCTYPE html> <html> <head> <style> div {/*from w w w. j ava2s . c o m*/ border: 1px solid black; margin: 5px; } </style> </head> <body> <button onclick="myFunction()">Test</button> <div id="myDIV"> <p>First p element</p> <p>Second p element</p> </div> <p id="demo"></p> <script> function myFunction() { var c = document.getElementById("myDIV").childElementCount; document.getElementById("demo").innerHTML = c; } </script> </body> </html>
The returned value contains the number of child element nodes, not the number of all child nodes such as text and comment nodes.
This property is read-only.
We can use the children property to return any child element of a specified element.
The childElementCount property has the same result as element.children.length.
The childNodes property contain all nodes, including text nodes and comment nodes.
The children property only contain element nodes.