Use attachShadow to attach a shadow root to a custom element. The method returns the root reference, which lets you populate the component even when its mode is closed. section 8.2
Create and populate an open shadow root
In connectedCallback(), call this.attachShadow({mode: 'open'}), then assign markup through this.shadowRoot.innerHTML. Open mode also exposes the root through the element’s shadowRoot property. section 8.2
Keep the returned reference in closed mode
const root = this.attachShadow({mode: 'closed'}); root.innerHTML = `<div class="inside-component">My Component</div>` A closed root makes shadowRoot null, but the return value remains usable inside the creating function. section 8.2
Closed mode limits ordinary access rather than providing real security: attachShadow can be replaced before component creation, defeating the intended isolation. section 8.2
Listing 8.2. Using the Shadow DOM in a simple component
connectedCallback() {
this.attachShadow({mode: 'open'}); #1
this.shadowRoot.innerHTML =
`<div class="inside-component">My Component</div>` #2
}
See the minimal component example that attaches an open shadow root and writes its internal markup. section 8.2
