JavaScript Reference ยท DOM: Document and Elements
Node.contains()
Reference for Node.contains(): test whether a node is the same as, or a descendant of, another node, with click-outside examples and shadow DOM caveats.
The contains() method answers one question: is this other node inside me? It returns true if the argument is a descendant of the node (a child, a grandchild, and so on) or the node itself, and false otherwise.
A typical use is "click outside to close": on each click you check whether the clicked element is inside a menu, and close the menu if it is not.
if (!menu.contains(event.target)) { closeMenu(); }
Try it
Syntax
node.contains(otherNode)
| Name | Description |
|---|---|
otherNode |
The node to look for. It may be any kind of node, such as an element or a text node. null is allowed. |
Return value: true if otherNode is node or one of its descendants, otherwise false (also for null).
Exceptions: TypeError if the argument is something other than a node or null, for example a string.
Usage notes
- A node contains itself.
el.contains(el)istrue. Compare withel !== otherwhen you need strict descendants only. - Direction matters.
parent.contains(child)istrue,child.contains(parent)isfalse. - Works on any node.
document.contains(element)is a quick way to find out whether an element is attached to the page. TheisConnectedproperty says the same thing for one node. - Detached trees. Elements that were created or removed but are not in the document are not contained by
document, though they can still contain their own children. - Shadow DOM.
contains()does not look inside a shadow tree: a host element does not "contain" nodes in its shadow root. To test across the boundary, useevent.composedPath().includes(node). - More detail. For the full relationship (preceding, following, contained by), see
compareDocumentPosition(). - Alternative with selectors. To find which ancestor matches a selector, use
closest(); to test containment of a specific node, usecontains(). - Click targets can disappear. If a click handler removes the clicked element, a later
contains()check may fail because the target is now detached. Check before you update the DOM.
Browser support
Supported in every browser.
Related
Element.closest()โ nearest ancestor matching a selectorElement.matches()โ test one element against a selectorparentElement,childrenand siblings โ tree navigation- Lesson: The DOM
- Lesson: Event delegation