Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
if (!menu.contains(event.target)) {
  closeMenu();
}

Try it

Click inside or outside
Edge cases

Syntax

JavaScript
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) is true. Compare with el !== other when you need strict descendants only.
  • Direction matters. parent.contains(child) is true, child.contains(parent) is false.
  • Works on any node. document.contains(element) is a quick way to find out whether an element is attached to the page. The isConnected property 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, use event.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, use contains().
  • 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.