Node: contains() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

The contains() method of the Node interface returns a boolean value indicating whether a node is a descendant of a given node, that is the node itself, one of its direct children (childNodes), one of the children's direct children, and so on.

Note: A node is contained inside itself.

Syntax

js
contains(otherNode)

Parameters

otherNode

The Node to test with.

Note: otherNode is not optional, but can be set to null.

Return value

A boolean value that is true if otherNode is contained in the node, false if not.

If the otherNode parameter is null, contains() always returns false.

Example

This function checks to see if an element is in the page's body. As contains is inclusive and determining if the body contains itself isn't the intention of isInPage this case explicitly returns false.

js
function isInPage(node) {
  return node === document.body ? false : document.body.contains(node);
}

Specifications

Specification
DOM
# ref-for-dom-node-contains①

Browser compatibility

desktop mobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
contains
Chrome – Full support
Chrome 16 (Release date: 2011-12-13)
footnote Full support
Edge – Full support
Edge 12 (Release date: 2015-07-29)
footnote Full support
Firefox – Full support
Firefox 9 (Release date: 2011-12-20)
footnote Full support
Opera – Full support
Opera 7 (Release date: 2003-01-28)
footnote Full support
Safari – Full support
Safari 1.1 (Release date: 2003-10-24)
footnote Full support
Chrome Android – Full support
Chrome Android 18 (Release date: 2012-06-27)
footnote Full support
Firefox for Android – Full support
Firefox for Android 9 (Release date: 2011-12-21)
footnote Full support
Opera Android – Full support
Opera Android 10.1 (Release date: 2010-11-09)
footnote Full support
Safari on iOS – Full support
Safari on iOS 1 (Release date: 2007-06-29)
footnote Full support
Samsung Internet – Full support
Samsung Internet 1 (Release date: 2013-04-27)
footnote Full support
WebView Android – Full support
WebView Android 4.4 (Release date: 2013-12-09)
footnote Full support
WebView on iOS – Full support
WebView on iOS 1 (Release date: 2007-06-29)
footnote Full support

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

See also