Sometimes, we want to check if element has any children in JavaScript.
In this article, we’ll look at how to check if element has any children in JavaScript.
How to check if element has any children in JavaScript?
To check if element has any children in JavaScript, we can use various properties of the element.
For instance, we write
if (element.firstChild) {
// ...
}
if (element.hasChildNodes()) {
// ...
}
if (element.childNodes.length > 0) {
// ...
}
to check if the firstChild
is available with element.firstChild
,.
If it’s set, then element
has at least one child.
We can also call hasChildNodes
to check if it has any child elements.
Or we can check if element.childNodes.length
is bigger than 0 to do the same thing.
Conclusion
To check if element has any children in JavaScript, we can use various properties of the element.