Favorites

DOM Node.contains() Method

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
Node.contains()
DOM Node MethodThis method is supported by all modern browsers.
Updated 28th November 2026

The contains() method checks whether a node is inside another node (or is the same node).

Description

The contains() method returns true if the given node is a descendant of this node, or the node itself. A common use is closing a menu or popup when the user clicks outside it: check whether menu.contains(event.target).

It returns true when the node is passed itself, so el.contains(el) is true. Passing null returns false. It only searches the light DOM, so nodes inside a shadow root aren't considered descendants of the host element.

For the "click outside to close" pattern, listen on the document and check menu.contains(event.target); when the pointer is inside the menu, the check passes and the menu stays open. event.composedPath().includes(menu) does the same job across shadow DOM boundaries.

Syntax

node.contains(otherNode)

Parameters

  • otherNodeThe node to look for.

Return Value

true if the other node is this node or one of its descendants, otherwise false.

Example

<nav id="menu" style="padding:8px;background:#eef"><a href="#">Link</a></nav>
<p>Click inside or outside the menu.</p>
const menu = document.getElementById('menu');
document.addEventListener('click', e => {
  console.log(menu.contains(e.target) ? 'inside the menu' : 'outside the menu');
});
console.log(menu.contains(menu.querySelector('a')), menu.contains(document.body));

Browser Support

The following information will show you the current browser support for the Node.contains() method. Hover over a browser icon to see the version that first introduced support for this method.

This method is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee