liveBook · Manning

attachShadow

As explained in Web Component Development with Modern Libraries and Tooling

A browser method that attaches a shadow root to an element and returns the resulting ShadowRoot object.

attachShadow attaches a shadow root to a custom element and returns the resulting ShadowRoot. A typical component creates it in its constructor with mode set to "open" or "closed". section 3.6 section 4.2.2

Create an open shadow root

class SortableTable extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); } } An open root is available through this.shadowRoot, so component code can add content with this.shadowRoot.innerHTML or this.shadowRoot.replaceChildren(...). section 3.6 section 4.2.2

Choose the mode according to how the component should be inspected and integrated:

  • Use "open" when debugging, testing, or allowing code to query descendants through the element's shadowRoot property. section 3.6
  • Use "closed" only with care: attachShadow still returns the ShadowRoot, but the instance does not receive a shadowRoot property. section 3.6
  • Create the root in the constructor when initialization should happen once per instance; connectedCallback runs every time the instance is attached. section 4.2.2
  • If creation is delayed until connectedCallback, guard against detached elements being reattached; this allows attribute values to be available before rendering. section 4.2.2
constructor() {
  super();
  this.attachShadow({ mode: "open" });
}

Use the compact constructor pattern to attach an open shadow root to each component instance. section 3.6

How Web Component Development with Modern Libraries and Tooling covers it

How deep it goes
Explains modes, returned references, lifecycle placement, content insertion, and querying, but not ShadowRoot internals.
Examples
Uses constructor listings, HTML-string or DOM-node insertion, and querying a table inside car-table elements.
What it assumes
Assumes familiarity with custom-element classes, constructors, connectedCallback, and basic DOM querying.
What you can do after
Build it from scratch by attaching, populating, and querying an open shadow root in a custom element.
How it connects
Connects Shadow DOM with ShadowRoot, web components, constructors, connectedCallback, and querySelector.

Also explained in

Compare how 3 books explain attachShadow →

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.