Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Element.attachShadow — attaching a Shadow DOM tree

Element.attachShadow() attaches a Shadow DOM root to a supported element and returns a ShadowRoot. The required open or closed mode controls access through host.shadowRoot, not a security boundary.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

const root = element.attachShadow({ mode: "open" });

Element.attachShadow() creates a Shadow DOM tree associated with a host element and returns its ShadowRoot. This is a separate tree: its nodes do not become ordinary children of the host. Consequently, host.querySelector() does not search inside it; call the method on the returned root instead.

The mode option is required. With "open", host.shadowRoot exposes the root; with "closed", it returns null. In both modes, attachShadow() returns the root, so a retained reference still lets you modify it. "closed" does not secure confidential data.

Not every element can be a host: div is supported, but input, for example, is not. An unsupported host or attaching again to an ordinary existing root causes NotSupportedError. An existing declarative root is an exception: a matching mode allows reuse but clears its contents; a mismatched mode causes an error.

This is a browser DOM API, not a feature of a particular ECMAScript edition. Check typeof Element.prototype.attachShadow === "function" in the target browser; this does not establish support for every additional option. Node 24 in the repository does not prove support for this API.

Examples

(() => {
  const host = document.createElement("div");
  const root = host.attachShadow({ mode: "open" });
  const label = document.createElement("span");
  label.textContent = "Hello";
  root.append(label);

  console.log(host.shadowRoot === root);
  console.log(host.querySelector("span") === null);
  console.log(root.querySelector("span").textContent);
})();

Result

true
true
Hello

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources