Use `Element.attachShadow()` when a custom element needs an internal DOM tree for its markup and styles. Call it on the host, usually in the constructor. It returns a `ShadowRoot` that component code can use for rendering. section 7.8.1 section 7.5
Pass an options object when attaching the root:
- `mode` is required. With `open`, the host’s `shadowRoot` property exposes the root. With `closed`, that property returns `null`; keep the returned reference if component code needs it. Closed mode is not a security boundary and provides no additional style isolation. section 7.8.1 section 7.8.3
- `delegatesFocus: true` moves focus into the first focusable element in the shadow tree when the host receives focus. section 7.8.1
- `slotAssignment` is `named` by default; `manual` lets component code assign nodes with `slot.assign()`. section 7.8.1
Render into the root, not the host
An open-root custom element can call `this.attachShadow({ mode: 'open' })` in its constructor, then set `this.shadowRoot.innerHTML` when rendering. Setting `this.innerHTML` instead adds light-DOM nodes to the host; those nodes appear in the shadow tree only if a `<slot>` projects them. Attributes, properties, and events still belong on the host. section 7.8.1
Listing 7.4 A web component using shadow DOM
<style>
button {
background-color: black;
color: white;
}
</style>
<script>
class MyComponent extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' }); #1
}
connectedCallback() {
this.shadowRoot.innerHTML = ` #2
<style>
h1 {
border: 1px solid gray;
}
</style>
<button>Click me</button>
`;
}
}
customElements.define('my-component', MyComponent);
</script>
<h1>CSS with components</h1>
<my-component></my-component>
The component renders a button and its styles inside an open shadow root while page-level markup and styles remain outside it. section 7.8.3
When hydrating a declarative shadow root, check for an existing root before calling `attachShadow()`. A matching mode clears and returns the existing root, destroying server-rendered content; a mismatched mode throws. For open or closed declarative roots, `attachInternals().shadowRoot` can locate the root before a fallback call to `attachShadow()`. section 9.6.3


