DOM Methods
Element.attachShadow()
Attaches a shadow root to a supported host element. mode controls whether host.shadowRoot exposes it. An existing non-declarative root normally prevents attaching another. Closed mode is encapsulation, not a security boundary. If an existing root was declared during parsing, calling attachShadow with the same mode clears that declarative root and returns it. To preserve server-rendered contents, check for an existing accessible root first. A different mode or existing non-declarative root can cause NotSupportedError. Example result: true.
Formal Syntax & Structure
html syntaxhtml
host.attachShadow(options)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| options | ShadowRootInit | Requires mode open or closed; optional settings such as delegatesFocus. |
Return Value
ShadowRoot
New shadow root, or matching declarative root cleared for reuse.
Working Example
Example Snippethtml
<p> Result: <output id="result"></output></p><script> const result = document.getElementById("result"); (async () => { const host = document.createElement("div"); document.body.append(host); const root = host.attachShadow({mode: "open"}); root.textContent = "Inside"; result.textContent = root === host.shadowRoot; })().catch(error => { result.textContent = "Error: " + error.name; });</script>