Check if a Span element is Empty using JavaScript

avatar

Borislav Hadzhiev

Mon Jan 10 20222 min read

Check if a Span element is Empty using JavaScript #

Use the childNodes property to check if a span 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 span 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> <span id="container"></span> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const span = document.getElementById('container'); if (span.childNodes.length === 0) { console.log('✅ Span element is empty'); } else { console.log('⛔️ Span 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 the length property returns a value greater than 0, then the span element is not empty.

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 span element is empty.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <span id="container"> <!-- my comment here --> </span> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const span = document.getElementById('container'); if (span.textContent.trim() === '') { console.log('✅ Span element is empty'); } else { console.log('⛔️ Span element is not empty'); }

We used the textContent property to get the text content of the span 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.