liveBook · Manning

Shadow root

As explained in Web Component Development with Modern Libraries and Tooling

The browser object representing the root of a shadow DOM tree.

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

How Web Component Development with Modern Libraries and Tooling covers it

How deep it goes
Explains creation, open or closed access, internal queries, rendering methods, and template cloning, but not deeper browser internals.
Examples
Uses custom elements, sortable tables, template cloning, internal table queries, and DevTools inspection of shadow roots.
What it assumes
Assumes familiarity with web components and DOM methods while demonstrating shadow-root rendering from basic attachment onward.
What you can do after
Build vanilla web components that attach, render, update, query, and inspect their shadow DOM.
How it connects
Connects shadow roots with web components, shadow DOM, custom elements, connectedCallback, templates, and querySelector.

Also explained in

Compare how 3 books explain shadow root →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Component Development with Modern Libraries and Tooling. The section links point to the parts of the book it draws on.