A reusable component may need its own markup and CSS without changing the rest of the page. Shadow DOM gives a custom element a separate DOM tree for that content. The surrounding document is called the light DOM. Without this boundary, a component’s table styles might affect every table on the page, while page code might accidentally change the component’s internal elements. section 3.6
A radio group with its own markup
A <radio-group> element can accept labels, values, and a selected value as attributes. Its shadow tree contains the fieldset, radio buttons, and component styles. A template supplies the shared structure; each instance clones it and renders the resulting nodes into its shadow root. Named slots leave places for page-provided content before and after the buttons. section 3.10
The boundary changes how page code interacts with a component:
- Component styles do not leak into the light DOM, and ordinary page styles do not style shadow-tree elements; there are exceptions that permit deliberate customization. section 3.6
- Document-level querySelector calls do not find shadow-tree elements. With an open shadow root, code can deliberately query an instance’s shadowRoot instead. section 3.6
- An event from inside the shadow tree bubbles out only when both its bubbles and composed properties are true. section 3.6
For a vanilla custom element, attach the root once in its constructor with this.attachShadow({ mode: "open" }); then render into this.shadowRoot. Open mode makes inspection, testing, and integration easier. Closed mode does not provide a reliable security boundary. Attaching in connectedCallback can leave slotted children temporarily unstyled and must account for the element being connected again. section 3.6 section 4.2.2
Listing 3.15 radio-group template
const html = String.raw;
const template = document.createElement("template");
template.innerHTML = html`
<style>
:host {
display: block;
}
fieldset {
border-color: var(--border-color, black);
display: inline-flex;
flex-direction: column;
align-items: start;
gap: 0.5rem;
> legend {
color: var(--legend-color, black);
}
> div {
display: flex;
flex-direction: var(--direction, row);
gap: var(--gap, 1rem);
> div {
display: flex;
align-items: center;
gap: 0.25rem;
}
}
}
input {
margin: 0;
}
</style>
<fieldset>
<legend></legend> #1
<slot name="before"></slot>
<div></div> #2
<slot name="after"></slot>
</fieldset>
`;
The radio-group template places a style element, fieldset, and named slots together in the structure cloned into each shadow root. section 3.10
Use a shadow root when a component defines its own CSS and needs to avoid conflicts with page styles. It is not required for every web component, and open roots remain intentionally accessible through shadowRoot. section 4.2.1 section 4.2.2



