Node.contains(otherNode) returns a Boolean: true if otherNode is this node or a descendant (child, grandchild, …), otherwise false (MDN).
Baseline · Widely available: not Deprecated, Experimental, or Non-standard (since about July 2015).
Inclusive: a node contains itself — node.contains(node) is true. Passing null always returns false (MDN).
Remember
parent.contains(otherNode)
→ true if otherNode === parent
OR otherNode is under parent
→ false otherwise
→ false if otherNode is null
parent
└─ child
└─ grandchild ← parent.contains(grandchild) === true
Call it on the possible ancestor and pass the node you want to test.
Get the ancestor node (for example a container or document.body).
Call ancestor.contains(otherNode).
Treat true as “same node or somewhere underneath.”
Remember null → false; self → true.
Piece
Required?
Role
Receiver node
Yes
Possible ancestor (or self)
otherNode
Yes (may be null)
Node to test
Return value
—
true / false
Pseudocode
Pseudocode
function contains(self, other):
if other is null:
return false
if other is self:
return true
walk up from other via parentNode
return true if we reach self
return false
Reference
Cheat Sheet
Keep these facts handy when testing DOM ancestry.
Topic
Detail
Syntax
node.contains(otherNode)
Returns
true · false
Self
node.contains(node) === true
null
Always false
Depth
Any descendant level counts
vs bitmask API
compareDocumentPosition()
Status (MDN)
Baseline Widely available
Try it
Live Preview
Run contains() checks on a small tree: nested child, self, null, outside node, or MDN’s isInPage idea.
Hi
Outside
Browser demo of Node.contains() — inclusive descendants, null → false.
Result
Loading…
Code
JavaScript Examples
Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.
One line:ancestor.contains(node) is the simple yes/no for “same node or somewhere underneath.”
Frequently Asked Questions
It returns true if otherNode is this node or a descendant of this node (child, grandchild, and so on). Otherwise it returns false (MDN).
No. MDN marks Node.contains() as Baseline Widely available (since about July 2015). It is not Deprecated, Experimental, or Non-standard.
Yes. MDN notes that a node is contained inside itself, so node.contains(node) is true.
contains(null) always returns false. The argument is required in the signature but may be set to null (MDN).
contains answers a simple yes/no inclusive-descendant question. compareDocumentPosition returns a bitmask for order, containment, and disconnected cases.
MDN’s isInPage pattern: return false if the node is document.body itself, otherwise return document.body.contains(node).