Skip to content

Instantly share code, notes, and snippets.

@condor-bird
Created April 4, 2020 08:39
Show Gist options
  • Save condor-bird/92a86469aef849a124bd58225c6acd95 to your computer and use it in GitHub Desktop.
Save condor-bird/92a86469aef849a124bd58225c6acd95 to your computer and use it in GitHub Desktop.
How to check if element has any children in Javascript?
if (element.firstChild) {
// It has at least one
}
if (element.hasChildNodes()) {
// It has at least one
}
if (element.childNodes.length > 0) { // Or just `if (element.childNodes.length)`
// It has at least one
}
if (element.children.length > 0) { // Or just `if (element.children.length)`
// It has at least one element as a child
}
element.getElementsByTagName('*').length > 0
if (element.innerHTML.trim() !== '') {
// It has at least one
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment