CKTIS / JavaScript
Node.contains() and Node.isConnected: subtree vs. document
Use `contains()` to check membership in a specific node’s subtree and `isConnected` to check whether a node is connected to a document.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
container.contains(otherNode) // boolean; otherNode is a required argument that accepts a Node or null
node.isConnected // boolean; read-only propertyNode.contains/isConnected pairs two different DOM checks. container.contains(otherNode) returns true if otherNode is container itself or one of its direct or indirect descendants in the node tree. It works in a detached subtree, too. The argument is required: null returns false, but omitting it or passing a selector string throws TypeError.
node.isConnected is a read-only boolean property, not a method. It is true if the node’s root, after following any Shadow DOM hosts, is a Document. That need not be the current document, and the result says nothing about visibility. Detaching a subtree from a document makes isConnected become false for its nodes without changing their relationships within the subtree.
contains() does not cross a Shadow DOM boundary. A node in a shadow tree can have isConnected === true when the host is connected to a document, even though host.contains(shadowChild) returns false. Both are web DOM APIs, not ECMAScript 2024 features; availability depends on the runtime.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DOM checks</title>
</head>
<body>
<script>
{
const doc = document.implementation.createHTMLDocument("DOM checks");
const host = doc.createElement("div");
const child = doc.createElement("span");
const shadow = host.attachShadow({ mode: "open" });
const shadowChild = doc.createElement("span");
host.appendChild(child);
shadow.appendChild(shadowChild);
const report = (label) => {
console.log(`${label}: ${host.contains(child)} ${child.isConnected}`);
};
console.log(`self/null: ${host.contains(host)} ${host.contains(null)}`);
report("before");
doc.body.appendChild(host);
report("attached");
console.log(`shadow: ${host.contains(shadowChild)} ${shadow.contains(shadowChild)} ${shadowChild.isConnected}`);
host.remove();
report("detached");
}
</script>
</body>
</html>Result
self/null: true false before: true false attached: true true shadow: false true true detached: true false
Save the example as an HTML file, open it in a browser, and check the output in the developer console. It creates a separate HTML document and leaves the open page unchanged. Removing the host still leaves `child` inside it, but `child.isConnected` becomes `false` again.
Related lessons
- JavaScript · Lesson 40 · Intermediate · Version: 3