Check if a Div element is Empty using JavaScript

avatar

Borislav Hadzhiev

Mon Jan 10 20222 min read

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 in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"></div> <script src="index.js"></script> </body> </html>

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'); }

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 event a comment inside it, it would be included in the NodeList the childNodes property returns.

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> <meta charset="UTF-8" /> </head> <body> <div id="box"> <!-- this is a comment --> </div> <script src="index.js"></script> </body> </html>

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'); }

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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee