How to check in JavaScript if one element is contained within another
Here, isContained
is true if child
is directly or indirectly nested inside parent
, false otherwise.
Less obvious scenarios
Sometimes, your elements don't have a direct parent-child relationship. In such cases, you may traverse up the DOM tree:
This function is handy when child
could be deeply nested within parent
.
Alternative containment checks
The querySelector
introduces another way to hunt down elements:
It returns true if any .child
is found inside parent
, at any depth. Even Nemo's deep.
Digging deeper
Need more details about the relationship between two nodes? compareDocumentPosition
got ya:
isContained
is true if child
is inside parent
, and it uses bitwise operations for a more granular check. Fancy enough?
Consider inconsistent browser behavior
Despite contains()
being fairly broadly supported, be aware of different browser behaviors. Using polyfills can help iron out any inconsistencies.
Consider performance
contains()
is fast but if dug deep in a large DOM or calling frequently, saving the result for future use can optimize performance.
Error prevention
Do validate inputs to avoid walking into errors like TypeError: Cannot read property 'contains' of null
.
Tailored solutions
Every project differs. Whether it's checking for multiple elements or complex conditions, consider glueing contains()
with other query methods or logic.
Was this article helpful?