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


