JavaScript Node contains() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Instance method

What You’ll Learn

The Node.contains() method returns whether another node is this node or a descendant of it. Learn the inclusive self-check, null behavior, the MDN isInPage pattern, and how it compares to compareDocumentPosition().

01

Kind

Instance method

02

Returns

boolean

03

Inclusive

Contains itself

04

null

Always false

05

Checks

Descendants

06

Status

Baseline widely

Introduction

When you need a simple yes/no answer—“is this node inside that container?”— contains() is the clearest API. It walks the descendant relationship, not just direct children.

One beginner surprise: a node contains itself. If you only care about true descendants (or “is this in the page body?”), exclude the self case explicitly, as MDN’s isInPage example does.

💡
Beginner tip

Read parent.contains(child) as “is child inside parent (or equal to it)?” The receiver is the container.

Understanding contains()

MDN: contains() returns whether a node is a descendant of a given node— itself, a direct child, a grandchild, and so on.

  • TrueotherNode is this node or nested under it.
  • False — not in the subtree (or otherNode is null).
  • Inclusivenode.contains(node) is true.
  • Not only Elements — works with Node; text nodes can be tested too.

📝 Syntax

JavaScript
const inside = node.contains(otherNode);

Parameters

  • otherNode — The node to test. Not optional in the signature, but may be null (then the result is always false).

Return value

A boolean: true if otherNode is contained in the node, otherwise false.

⚖️ contains() vs compareDocumentPosition()

contains()compareDocumentPosition()
Returnstrue / falseBitmask of position flags
Best forIs other inside me?Order + containment + disconnected
Selftrue (inclusive)0
Before / afterNot reportedPRECEDING / FOLLOWING
Beginner usePreferred for simple checksWhen you need more than yes/no

⚡ Quick Reference

GoalCode
Is child inside parent?parent.contains(child)
Self checknode.contains(node)true
Null argumentnode.contains(null)false
In page body (strict)node === document.body ? false : document.body.contains(node)
Not a descendant!container.contains(other)
MDN statusBaseline Widely available (since July 2015)

🔍 At a Glance

Four facts to remember about Node.contains().

Returns
boolean

true / false

Baseline
widely

Since July 2015

Self
true

Inclusive

null
false

Always

Examples Gallery

Examples follow MDN Node.contains() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

Descendants, inclusive self, and nodes outside the subtree.

Example 1 — Parent Contains a Nested Child

Any depth of nesting counts as contained.

JavaScript
const parent = document.getElementById("parent");
const child = document.getElementById("child");

console.log(parent.contains(child)); // true
Try It Yourself

How It Works

child lives under parent in the tree, so contains returns true even if there are wrappers in between.

Example 2 — A Node Contains Itself

MDN: a node is contained inside itself.

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

How It Works

Inclusive containment is intentional. Exclude the self case when your logic needs strict descendants only.

📈 Outside, Null & In-Page Checks

False cases and the MDN body helper.

Example 3 — Node Outside the Subtree

Siblings and unrelated branches return false.

JavaScript
const left = document.getElementById("left");
const right = document.getElementById("right");

console.log(left.contains(right)); // false
console.log(right.contains(left)); // false
Try It Yourself

How It Works

Neither node is under the other. Direction matters: always call container.contains(maybeChild).

Example 4 — null Always Returns false

Useful when a lookup might miss.

JavaScript
const host = document.getElementById("host");
const missing = document.getElementById("nope"); // null

console.log(host.contains(null));    // false
console.log(host.contains(missing)); // false
Try It Yourself

How It Works

MDN: if otherNode is null, contains() always returns false—no throw.

Example 5 — Is the Node in the Page Body? (MDN)

Exclude document.body itself when that is not what you want.

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

const el = document.getElementById("target");
console.log(isInPage(el));            // true
console.log(isInPage(document.body)); // false
Try It Yourself

How It Works

Because contains is inclusive, MDN’s helper returns false for document.body itself, then uses document.body.contains(node) for everything else.

🚀 Common Use Cases

  • Click-outside / dismiss: is the event target inside a modal or menu?
  • Confirm a node still lives under a known container before updating UI.
  • Validate drag-and-drop drop targets within a region.
  • Check whether a selection or focus target is inside an editor root.
  • Guard helpers like isInPage without treating body as “in page” when unwanted.

🔧 How It Works

1

Call on the container

container.contains(otherNode) — receiver is the ancestor candidate.

Call
2

Handle null / self

null → false; same node → true.

Edge
3

Walk descendants

True if otherNode is anywhere under the container’s subtree.

Tree
4

Boolean result

Branch your UI logic with a clear true / false.

📝 Notes

Universal Browser Support

Node.contains() is Baseline Widely available across modern browsers (MDN: since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline · Widely available

Node.contains()

Safe for production. Remember inclusive self and null → false.

Universal Widely available
Google Chrome Full support · Desktop & Mobile
Full support
Mozilla Firefox Full support · Desktop & Mobile
Full support
Apple Safari Full support · macOS & iOS
Full support
Microsoft Edge Full support · Chromium & Legacy
Full support
Opera Full support · Modern versions
Full support
Internet Explorer Long-standing support in legacy IE
Full support
contains() Excellent

Bottom line: Use contains for simple inside-subtree checks; use compareDocumentPosition when you also need document order.

Conclusion

Node.contains() answers whether another node is this node or a descendant. Watch the inclusive self case, treat null as false, and reach for compareDocumentPosition when you need order as well.

Continue with getRootNode(), compareDocumentPosition(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Call container.contains(maybeChild)
  • Handle the inclusive self case when needed
  • Use for click-outside and region checks
  • Pass lookup results that might be null safely
  • Prefer this over bitmasks for simple inside tests

❌ Don’t

  • Forget that node.contains(node) is true
  • Reverse container and child without noticing
  • Assume only Elements work (Nodes do)
  • Confuse DOM Node with the Node.js runtime
  • Use contains when you need before/after order

Key Takeaways

Knowledge Unlocked

Five things to remember about contains()

Boolean descendant check, inclusive of self.

5
Core concepts
🔄 02

Inclusive

contains self

Gotcha
03

null → false

safe miss

Edge
📁 04

Any depth

not only kids

Tree
📄 05

isInPage

exclude body

Pattern

❓ 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.
No. MDN marks Node.contains() as Baseline Widely available (since July 2015). It is a standard DOM method — 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.
contains answers a simple yes/no descendant (inclusive) 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).
Did you know?

Click-outside handlers often use !menu.contains(event.target) so a click anywhere outside the menu closes it— including when event.target is a text node inside another element.

Next: getRootNode()

Find the Document, ShadowRoot, or top of a detached tree.

getRootNode() →

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.

5 people found this page helpful