The DOM childElementCount property is used to count the number of child elements and return it. It counts only child elements except for text and comment nodes.Â
Syntax
node.childElementCount- node: node is an object that represents the document or element.Â
- Return Value: It returns the number of child elements of the given element.Â
Example: In this example, we will see the use of the DOM childElementCount property
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
DOM childElementCount Property
</title>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>
DOM childElementCount Property
</h2>
<p>Searching Algorithms</p>
<ul id="parent">
<li>Merge sort</li>
<li>Quick sort</li>
</ul>
<!--Driver Code Ends-->
<button onclick="geek()">Click Here!</button>
<p id="p"></p>
<script>
function geek() {
let doc =
document.getElementById("parent").childElementCount;
document.getElementById("p").innerHTML =
"No of entries: " + doc;
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
- Unlike childNodes.length (which includes all node types), childElementCount returns only the number of element children. Text nodes, comment nodes, and other non-element nodes are excluded.
- element.childElementCount always returns the same value as element.children.length. The children property gives you the live HTMLCollection of child elements, while childElementCount is a convenient shortcut that just returns the count.