A shadow root is the browser object that contains a web component’s private DOM tree. Attach one with attachShadow({ mode: "open" }) or attachShadow({ mode: "closed" }). Open mode exposes the component’s shadowRoot property, making debugging, testing, and internal queries easier; closed mode returns the object but hides that property and complicates integration. section 3.6
A component with an open shadow root
A vanilla web component can create its shadow root in the constructor, then render into it from connectedCallback. Use shadowRoot.replaceChildren(...) for a complete update, or appendChild(...) when adding content without replacing existing children. section 3.6 section 4.2.3
constructor() {
super();
this.attachShadow({ mode: "open" });
}
Creates an open shadow root whose ShadowRoot object remains available through the component’s shadowRoot property. section 3.6
Use the shadow root to:
- Render HTML strings or DOM nodes into the component. section 3.6
- Find internal elements with this.shadowRoot.querySelector(...) when the mode is open. section 3.6
- Keep ordinary searches outside the component from finding elements rendered inside it. section 3.6
- Render larger structures from a template by cloning template.content and replacing the shadow root’s contents. section 4.2.3
// Outside the web component class ...
const template = document.createElement("template");
template.innerHTML = html`...add HTML here`;
// In a method of the web component class ...
const element = template.content.cloneNode(true);
this.shadowRoot.replaceChildren(element);
Shows the reusable template pattern: define the HTML once, clone it for an instance, and place the clone into the shadow root. section 4.2.3


