Check if a Div element is Empty using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 5, 2024
2 min

banner

# Check if a Div element is Empty using JavaScript

Use the childNodes property to check if a div element is empty. The childNodes property returns a NodeList of the element's child nodes, including elements, text nodes and comments.

If the property returns a value of 0, then the div is empty.

Here is the HTML for the examples.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <div id="box"></div> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); if (box.childNodes.length === 0) { console.log('✅ Element is empty'); } else { console.log('⛔️ Element is NOT empty'); }

check if div element is empty

The code for this article is available on GitHub

The childNodes property returns a NodeList containing the element's child nodes, including:

  • child elements
  • text nodes
  • comment nodes
Accessing the length property on the NodeList returns the number of child nodes of the element.

If your element had a text node or even a comment inside it, it would be included in the NodeList the childNodes property returns.

# Ignoring comments

If you want to ignore comments, use the textContent property to check if the div is empty.

index.html
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> </head> <body> <div id="box"> <!-- this is a comment --> </div> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); if (box.textContent.trim() === '') { console.log('✅ Element is empty'); } else { console.log('⛔️ Element is NOT empty'); }

ignoring comments check if div is empty

The code for this article is available on GitHub

We used the textContent property to get the text content of the div element and its descendants.

We removed any leading or trailing whitespace using the trim() method and compared the result to an empty string.

If the element's textContent property is an empty string, then it is empty.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.