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".


<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    <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>
    <button type="button" onclick="execute()">Click Me</button>
    <p id="out"></p>
    function execute(){
        var element = document.getElementById('myElement');
        var count = element.childElementCount;
        document.getElementById('out').innerHTML = 'Number of Child Elements in #myElement: ' + count;
Try Online

There are three children for HTML element with id myElement, namely, a <p>, a <ul>, and a <div>.


In this JavaScript Tutorial, we learned how to get the number of child elements of an HTML Element using JavaScript.