How to Count Child Elements of a DOM Element in JavaScript

08/02/2021

Contents

In this article, you will learn how to count child elements of a DOM element in JavaScript.

Counting child elements of a DOM element in JavaScript

In JavaScript, you can count the number of child elements of a DOM element using the childElementCount property. This property returns an integer representing the number of child elements that the element has.

Example
const element = document.getElementById('myElement');
const childCount = element.childElementCount;
console.log(childCount); // Output: the number of child elements of the element

Note that the childElementCount property only counts the number of child elements, not including other types of child nodes such as text nodes or comment nodes.

Alternatively, you can use the children property to get a collection of all the child elements of an element, and then get the length of that collection to count the number of child elements.

Example
const element = document.getElementById('myElement');
const children = element.children;
const childCount = children.length;
console.log(childCount); // Output: the number of child elements of the element

This example first gets a collection of all the child elements of the element using the children property, and then gets the length of that collection using the length property.

It’s worth noting that the children property only returns child elements, not including other types of child nodes such as text nodes or comment nodes. If you need to count all types of child nodes, you can use the childNodes property instead and loop through the child nodes to count them.

Example
const element = document.getElementById('myElement');
const childNodes = element.childNodes;
let childCount = 0;
for (let i = 0; i < childNodes.length; i++) {
  if (childNodes[i].nodeType === 1) { // Check if the child node is an element node
    childCount++;
  }
}
console.log(childCount); // Output: the number of child elements of the element

This example first gets a collection of all the child nodes of the element using the childNodes property, and then loops through the child nodes to count the element nodes. The if statement checks if each child node is an element node using its nodeType property.