Skip to content
jshacks.dev
Browser

JavaScript element.contains(): Test Ancestry in the DOM

How JavaScript element.contains() tells whether a node is inside another, with outside clicks, shadow DOM limits, text nodes and compareDocumentPosition().

7 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the JavaScript, Google Chrome, NGINX, Postman and GraphQL logos.

A recurring question in interface code is whether one node sits inside another. Did the click land inside the menu or outside it? Is the focused element part of this dialog? Did the mutation happen under the container I care about? node.contains(other) answers that with a boolean. It is a small method with a few behaviors that are worth knowing before you build an outside-click handler or a focus trap on top of it: it includes the node itself, it does not cross shadow boundaries, it accepts any node type and it is not the same as a selector test. This post explains how element.contains() works in JavaScript, how to use it for outside-click detection and focus checks, what it does with text nodes, null and detached trees, how it behaves with shadow DOM and composedPath(), and how it relates to compareDocumentPosition() and closest(). It is part of the DOM Standard's Node interface, documented on MDN, and works in all current browsers.

The basic form

parent.contains(child) returns true if child is parent itself or any of its descendants, at any depth, and false otherwise.

basic.jsJavaScript
document.body.innerHTML = `
  <div id="outer">
    <section id="inner"><p id="leaf">text</p></section>
  </div>
  <aside id="other"></aside>
`;

const outer = document.querySelector("#outer");
const leaf = document.querySelector("#leaf");
const other = document.querySelector("#other");

console.log(outer.contains(leaf));
console.log(outer.contains(other));
console.log(leaf.contains(outer));
console.log(outer.contains(outer));
Text
true
false
false
true

The last line is the part that surprises people: a node contains itself. If you want to know whether something is a strict descendant, exclude the node explicitly with parent !== child && parent.contains(child). The relationship is not symmetric, so leaf.contains(outer) is false.

Outside-click detection

The textbook use is closing a popup when the user clicks anywhere else. Attach one listener to the document and check whether the click target is inside the popup.

outside.jsJavaScript
document.body.innerHTML = `
  <button id="open">Menu</button>
  <div id="menu"><button id="item">Item</button></div>
  <p id="page">page</p>
`;

const menu = document.querySelector("#menu");
const opener = document.querySelector("#open");
let open = true;

document.addEventListener("click", (event) => {
  if (!open) return;
  if (menu.contains(event.target) || opener.contains(event.target)) return;
  open = false;
  menu.hidden = true;
  console.log("closed");
});

document.querySelector("#item").click();
console.log("still open:", open);
document.querySelector("#page").click();
Text
still open: true
closed

The handler also excludes the opener button, because without that check the same click that opens the menu would bubble up to the document and close it at once. A common variant uses pointerdown instead of click, so the menu closes before focus changes, and passes { capture: true } so that a handler that calls stopPropagation() somewhere else in the page cannot hide the event. Remember to remove the document listener when the popup closes or the component is destroyed.

cleanup.jsJavaScript
function onOutsideClick(element, callback) {
  const controller = new AbortController();

  document.addEventListener(
    "pointerdown",
    (event) => {
      if (!element.contains(event.target)) callback(event);
    },
    { signal: controller.signal, capture: true },
  );

  return () => controller.abort();
}

const panel = document.createElement("div");
document.body.append(panel);

const stop = onOutsideClick(panel, () => console.log("outside"));
stop();
Text
(no output: the listener was removed before any event)

Focus checks

document.activeElement is the focused element, and contains() tells whether it lives inside a given region. That is how you decide whether focus is still in a dialog or must be pulled back.

focus.jsJavaScript
document.body.innerHTML = `
  <div id="dialog"><input id="a"><button id="b">OK</button></div>
  <input id="outside">
`;

const dialog = document.querySelector("#dialog");

document.querySelector("#a").focus();
console.log(dialog.contains(document.activeElement));

document.querySelector("#outside").focus();
console.log(dialog.contains(document.activeElement));
Text
true
false

In a focusout handler, the element receiving focus is event.relatedTarget, which is null when focus leaves the window, so test it as dialog.contains(event.relatedTarget). Since contains(null) returns false rather than throwing, the common case is handled without a guard.

related.jsJavaScript
const box = document.createElement("div");
console.log(box.contains(null));
Text
false

Any node type

The argument can be any Node, not just an element, so text nodes and comments work, and the receiver can be a Document or a DocumentFragment too.

types.jsJavaScript
const p = document.createElement("p");
p.append("hello");
document.body.append(p);

console.log(p.contains(p.firstChild));
console.log(document.contains(p));
console.log(document.documentElement.contains(document.body));
Text
true
true
true

document.contains(node) is a way of asking whether a node is attached to the page, and node.isConnected is the more direct property for the same purpose, which also handles shadow trees. A detached tree has its own universe: nodes in it contain each other, but document.contains() is false for all of them.

detached.jsJavaScript
const root = document.createElement("div");
const child = document.createElement("span");
root.append(child);

console.log(root.contains(child));
console.log(document.contains(child));
console.log(child.isConnected);
Text
true
false
false

It does not cross shadow roots

Inside a shadow tree, the nodes belong to the shadow root, and host.contains(nodeInsideShadow) is false, because the shadow tree is not part of the host's light DOM children. That is the encapsulation working as intended, and it breaks outside-click detection for web components if you test event.target, since events from inside a shadow tree are retargeted to the host when seen from outside.

shadow.jsJavaScript
const host = document.createElement("div");
document.body.append(host);
const root = host.attachShadow({ mode: "open" });
root.innerHTML = "<button id='b'>in</button>";

const button = root.querySelector("#b");

console.log(host.contains(button));
console.log(root.contains(button));
console.log(host.shadowRoot.contains(button));
Text
false
true
true

For events, use event.composedPath(), the list of every node the event traveled through, including shadow internals when the shadow root is open. Checking event.composedPath().includes(menu) works across shadow boundaries, where menu.contains(event.target) does not.

path.jsJavaScript
document.addEventListener("click", (event) => {
  const inside = event.composedPath().includes(menuElement);
  if (!inside) closeMenu();
});
Text
(a click inside a shadow tree under menuElement still counts as inside)

contains() versus compareDocumentPosition()

compareDocumentPosition() gives a bit mask that describes the relationship between two nodes, including whether one is before the other in the document, and contains() is the quick yes or no for the ancestor case.

position.jsJavaScript
const outer = document.createElement("div");
const inner = document.createElement("span");
outer.append(inner);

const position = outer.compareDocumentPosition(inner);

console.log(Boolean(position & Node.DOCUMENT_POSITION_CONTAINED_BY));
console.log(outer.contains(inner));
Text
true
true

Use compareDocumentPosition() when you need order, for example to sort nodes into document order or to know whether a drop target is before or after the dragged node. Use contains() for membership.

contains() versus closest()

contains() takes a node you already hold. closest() takes a selector and searches for it. If you have the container in a variable, container.contains(target) is direct and cheap. If you need to find which of many possible containers holds the target, target.closest(".container") finds it without a list. The two combine in delegated handlers: closest() to find the candidate, then contains(candidate) on the delegate root to confirm it is inside, since closest() can match above the root.

Pitfalls

Forgetting that the node contains itself, which makes container.contains(event.target) true when the container is the target, usually what you want but not for a strict-descendant test. Testing event.target in a handler for components with shadow DOM. Calling contains() on a stale reference to an element that was replaced, which returns false for the new element. Using it on a selector string, which throws a TypeError, since the argument must be a node or null. And running it on every mousemove, where the answer rarely changes: track the state and update only when it flips.

Testing and practical notes

Code built on contains() is easy to test because the question has a definite answer: build a small tree, call the function with a node inside and a node outside, and assert the result. The cases worth covering are the node itself, a deeply nested descendant, a sibling, a detached node and null. For outside-click code, dispatch real events with dispatchEvent(new MouseEvent("pointerdown", { bubbles: true })) on elements inside and outside the panel, and check that the callback fires only for the outside one. Remember that bubbles: true is needed, otherwise the document listener never sees the event.

In practice, most bugs around outside clicks are not about contains() at all. They come from order of events: the click that opens a popup also reaches the document listener that closes it, because the listener was added too early. Add the document listener in a setTimeout or requestAnimationFrame, or compare against the opener, as in the example above. Another source is content that is removed from the page by the click handler itself, such as a menu item that rebuilds the list. By the time the document listener runs, the target element is detached, menu.contains(event.target) is false, and the menu closes when it should not. Using event.composedPath(), which is captured when the event is dispatched, avoids that, since the path is computed before handlers run.

Finally, prefer the platform's own behavior when it exists. A <dialog> opened with showModal() and a popover opened with the popover attribute both support light dismissal, so a click outside closes them without any script, and they handle focus correctly. Reach for contains() when you build something the platform does not provide.

Taggeddom
Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.