How to Check If a DOM Element has Children in JavaScript

08/02/2021

Contents

In this article, you will learn how to check if a DOM element has children in JavaScript.

Checking if a DOM element has children in JavaScript

In JavaScript, you can check if a DOM element has children using the hasChildNodes() method. This method returns a boolean value that indicates whether the element has any child nodes, including both element nodes and non-element nodes such as text nodes or comment nodes.

Example
const element = document.getElementById('myElement');
const hasChildren = element.hasChildNodes();
console.log(hasChildren); // Output: true if the element has children, false otherwise

This example first gets the element using the getElementById() method, and then checks if it has any children using the hasChildNodes() method. The hasChildren variable will be set to true if the element has children, and false otherwise.

Alternatively, you can check the childElementCount property to see if the element has any child elements specifically.

Example
const element = document.getElementById('myElement');
const hasChildren = element.childElementCount > 0;
console.log(hasChildren); // Output: true if the element has child elements, false otherwise

This example first gets the element using the getElementById() method, and then checks if it has any child elements using the childElementCount property. The hasChildren variable will be set to true if the element has child elements, and false otherwise.

It’s worth noting that the hasChildNodes() method and childElementCount property are not the same thing. The hasChildNodes() method checks if the element has any child nodes of any type, while the childElementCount property only counts the number of child elements specifically.