Last updated: Mar 5, 2024
Reading time·2 min
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.
<!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>
And here is the related JavaScript code.
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:
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.
If you want to ignore comments, use the textContent
property to check if the
div
is empty.
<!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>
And here is the related JavaScript code.
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.
trim()
method and compared the result to an empty string.If the element's textContent
property is an empty string, then it is empty.