A reusable component should not accidentally restyle the page around it—or have page code unexpectedly change its internal elements. Encapsulation keeps a component’s structure, styles, and behavior together while limiting unintended interactions with external code. Web components can achieve this with a shadow DOM. section 1.2 section 3.6
A table that stays in its lane
Imagine a <car-table> component with its own table styles. Without a shadow DOM, those styles could affect every table on the page, and outside code could find and modify the component’s table. Placing the table and its styles in a shadow DOM prevents those accidental interactions. section 3.6
constructor() {
super();
this.attachShadow({ mode: "open" });
}
The constructor attaches an open shadow root to the component. Its internal content and styles can then live behind that root. section 3.6
The boundary changes how the component interacts with the rest of the page:
- Component styles do not leak into the surrounding light DOM; outside styles generally do not affect shadow DOM elements, though there are exceptions. section 3.6
- Page-level querySelector calls do not discover internal elements. With an open shadow root, code can still query them through the component’s shadowRoot. section 3.6
- Internal events bubble out only when both their bubbles and composed properties are true. section 3.6
A web component does not have to use a shadow DOM. If it defines its own CSS, however, creating a shadow root is the recommended way to avoid conflicts with external CSS. Encapsulation reduces accidental interference; an open shadow root does not make internal elements inaccessible. section 4.2.1 section 3.6
















