ZetCode

ParentNode.childElementCount tutorial

last modified August 24, 2023

ParentNode.childElementCount tutorial shows how to count the number of child elements of an element in JavaScript in a document.

ParentNode.childElementCount

ParentNode.childElementCount returns the number of children of this ParentNode which are elements. The property is implemented both by document and element of the DOM.

To determine the child elements, we can use ParentNode.children property.

ParentNode.childElementCount example

The following example counts the number of child elements of a selected element. We select the element by clicking on it.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ParentNode.childElementCount</title>
    <link rel="stylesheet" href="main.css">
</head>
<body>

    <div id="first">
        <p>paragraph 1</p>
        <p>paragraph 2</p>
        <p>paragraph 3</p>
    </div>

    <div id="second">
        <p>paragraph 1</p>
        <p>paragraph 3</p>
    </div>

    <div id="output"></div>

    <button id="count">Count</button>

<script src="main.js"></script>
</body>
</html>

In the document, we have a couple of elements. The button event handler outputs the number of child elements in the output div.

main.css
* {
    margin:10px;
}

div {
    border: 1px solid steelblue;
    width: 200px; height: 150px;
}

This is some basic styling for the document.

main.js
let selected = document.body;

let btn = document.getElementById('count');
let output = document.getElementById('output');

btn.addEventListener('click', countElements);

function countElements(e) {

    let nOfElements = selected.childElementCount;
    output.innerHTML = `The ${selected.localName} has ${nOfElements} elements`;
}

document.onclick = e => {

    if (e.target.localName != 'button') {

        selected = e.target;
    }
}

There are two event handlers.

function countElements(e) {

    let nOfElements = selected.childElementCount;
    output.innerHTML = `The ${selected.localName} has ${nOfElements} elements`;
}

We determine the number of children with childElementCount property and output the message into the div's innerHTML.

document.onclick = e => {

    if (e.target.localName != 'button') {

        selected = e.target;
    }
}

We determine the clicked element in the document's handler. We skip the button element.

In this article we have shown how to count child elements of a DOM element.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.