Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Node.contains — checking DOM tree membership

Node.contains checks whether a given node is the node itself or a descendant at any depth. It returns a boolean.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

node.contains(other)

Node.contains is a Node instance method, called as node.contains(other). It returns true when other is node itself or a descendant at any depth; otherwise, it returns false. For null, the result is false.

The argument represents a node, not a CSS selector or search text. A descendant can also be a text node. To exclude the node itself, use node !== other && node.contains(other).

The current DOM tree matters, not visibility. The tree need not be attached to the document. The method does not cross shadow DOM boundaries: a descendant inside a shadow root is not thereby a descendant of its host. This is a DOM-standard Web API, not an ECMAScript language feature.

Examples

const root = document.createElement('div');
const child = document.createElement('span');
const text = document.createTextNode('Hello');
root.appendChild(child);
child.appendChild(text);

console.log(root.contains(root));
console.log(root.contains(child));
console.log(root.contains(text));
console.log(child.contains(root));
console.log(root.contains(null));
child.remove();
console.log(root.contains(text));

Result

true
true
true
false
false
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources