JavaScript – Number of Child Elements of HTML Element
To get the count or number of child elements of a specific HTML Element using JavaScript, get reference to this HTML element, and read the childElementCount
property of this HTML Element.
childElementCount
property returns the number of child elements in this HTML Element.
In the following example, we will get the number of child elements of the HTML Element which is selected by id "myElement"
.
example.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Get Number of Child Element in this HTML Element using JavaScript</h2>
<div id="myElement">
<p>Hello World!</p>
<ul><li>List Item</li></ul>
<div>Sample World</div>
</div>
<br>
<button type="button" onclick="execute()">Click Me</button>
<p id="out"></p>
<script>
function execute(){
var element = document.getElementById('myElement');
var count = element.childElementCount;
document.getElementById('out').innerHTML = 'Number of Child Elements in #myElement: ' + count;
}
</script>
</body>
</html>
There are three children for HTML element with id myElement
, namely, a <p>
, a <ul>
, and a <div>
.
Conclusion
In this JavaScript Tutorial, we learned how to get the number of child elements of an HTML Element using JavaScript.