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

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.
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));true
false
false
trueThe 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.
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();still open: true
closedThe 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.
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();(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.
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));true
falseIn 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.
const box = document.createElement("div");
console.log(box.contains(null));falseAny 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.
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));true
true
truedocument.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.
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);true
false
falseIt 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.
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));false
true
trueFor 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.
document.addEventListener("click", (event) => {
const inside = event.composedPath().includes(menuElement);
if (!inside) closeMenu();
});(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.
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));true
trueUse 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.


