JavaScript Node contains() Method

Beginner
5 min read
Updated: Oct 2026
5 examples
Live preview
Baseline

What Is contains()?

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
UsePrefer
Is this under that?ancestor.contains(node)
In the document body?MDN isInPage (exclude body itself)
Need order / bitmask?compareDocumentPosition()

How to Use contains()

Call it on the possible ancestor and pass the node you want to test.

  1. Get the ancestor node (for example a container or document.body).
  2. Call ancestor.contains(otherNode).
  3. Treat true as “same node or somewhere underneath.”
  4. Remember null → false; self → true.
PieceRequired?Role
Receiver nodeYesPossible ancestor (or self)
otherNodeYes (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

Cheat Sheet

Keep these facts handy when testing DOM ancestry.

TopicDetail
Syntaxnode.contains(otherNode)
Returnstrue · false
Selfnode.contains(node) === true
nullAlways false
DepthAny descendant level counts
vs bitmask APIcompareDocumentPosition()
Status (MDN)Baseline Widely available

Live Preview

Run contains() checks on a small tree: nested child, self, null, outside node, or MDN’s isInPage idea.

Browser demo of Node.contains() — inclusive descendants, null → false.

Result
Loading…

JavaScript Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — Nested Child

Any depth under the parent returns true.

JavaScript
const parent = document.getElementById("parent");
const child = document.getElementById("child");
console.log(parent.contains(child)); // true
Try It Yourself

How It Works

  1. Pick the ancestor. Call contains on the outer node.
  2. Pass the descendant. Nested depth does not matter.
  3. Get a Boolean. true means “under (or is) this node.”
  4. Common use. Click-outside and portal/menu checks.

Example 2 — A Node Contains Itself

MDN: a node is contained inside itself.

JavaScript
const el = document.getElementById("parent");
console.log(el.contains(el)); // true
Try It Yourself

How It Works

  1. Inclusive by design. Self counts as contained.
  2. Watch helpers. “Is in body?” often excludes body itself.
  3. Same reference. Identity equality is enough here.
  4. Contrast with parents. parentNode of the root of a check may be null.

Example 3 — contains(null)

Passing null always returns false (MDN).

JavaScript
const parent = document.getElementById("parent");
console.log(parent.contains(null)); // false
Try It Yourself

How It Works

  1. Argument may be null. Allowed by the API.
  2. Result is always false. No descendant to find.
  3. Safe for optional nodes. maybeEl && parent.contains(maybeEl) patterns work.
  4. Still required in signature. You must pass something — including null.

Example 4 — isInPage (MDN)

Check that a node is under document.body, excluding the body itself.

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

console.log(isInPage(document.getElementById("child")));
console.log(isInPage(document.body));
Try It Yourself

How It Works

  1. Exclude body. Inclusive contains would say body is “in” body.
  2. Delegate to contains. Everything under body returns true.
  3. Useful for cleanup. Know if a node is still attached under body.
  4. Not for detached trees. Nodes only in a DocumentFragment fail this check.

Example 5 — Outside the Tree

A sibling (or unrelated) node is not contained.

JavaScript
const parent = document.getElementById("parent");
const outside = document.getElementById("outside");
console.log(parent.contains(outside)); // false
Try It Yourself

How It Works

  1. Wrong ancestor. Sibling branches are not descendants.
  2. Returns false. No path from parent down to outside.
  3. Click-outside pattern. If click target is not contained, close the menu.
  4. Need richer relations? Use compareDocumentPosition().

Edge Cases & Pitfalls

Check these before relying on contains() in UI logic.

self

Inclusive of self

node.contains(node) is true. Helpers like isInPage often exclude that case on purpose.

null

null → false

Safe to pass null, but do not treat it as “missing argument error” — the result is simply false.

detached

Detached subtrees

A node only living in a fragment is not contained by document.body until you append it.

vs

Not a position bitmask

For preceding/following/disconnected details, use compareDocumentPosition() instead.

Browser Support

Node.contains() is Baseline Widely available (MDN, since about July 2015). Safe to use in modern and older evergreen browsers.

✓ Baseline · Widely available

Node.contains()

Supported across Chrome, Firefox, Safari, Edge, and Opera. Inclusive descendant check with null → false.

98% Modern browser support
Google Chrome contains() · full support
Full support
Microsoft Edge contains() · Chromium
Full support
Apple Safari contains() · modern versions
Full support
Mozilla Firefox contains() · modern versions
Full support
Opera contains() · modern versions
Full support
Internet Explorer contains() · IE9+
Legacy support
Node.contains() Excellent

Bottom line: Standard DOM ancestry check. Prefer it for yes/no containment; use compareDocumentPosition for richer relations.

Performance Notes

ApproachCostBest for
contains() onceCheap (engine-optimized)Click-outside / ancestry checks
Manual parent walkSimilar / more codeRarely needed
Call every animation frameWastefulAvoid — check on events

Use contains() on user events (click, focus), not in a tight timer loop.

Key Takeaways

  • Role: Boolean — is otherNode this node or under it?
  • Inclusive: node.contains(node) === true.
  • null: always returns false.
  • Pattern: MDN isInPage excludes document.body itself.

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).

Next: getRootNode()

Learn how node.getRootNode() returns the root of a node’s tree.

getRootNode tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful