Borislav Hadzhiev
Mon Jan 10 2022·2 min read
Photo by Artem Beliaikin
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.
<!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.
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:
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.
<!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.
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.
trim()
method and compared the result to an empty string.If the element's textContent
property is an empty string, then it is empty.