liveBook · Manning

Encapsulation

As explained in Web Component Development with Modern Libraries and Tooling

A design technique that isolates a component's internal structure, styles, and behavior from external code.

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

How Web Component Development with Modern Libraries and Tooling covers it

How deep it goes
Explains shadow DOM effects on styles, element queries, and events, while deferring styling exceptions and fuller event treatment.
Examples
Uses a car-table component whose CSS could affect other tables and whose internal elements could be modified by outside code.
What it assumes
Assumes basic HTML, CSS, and JavaScript familiarity while defining the DOM and encapsulation in plain language.
What you can do after
Operate/configure it by attaching a shadow root to a styled web component to avoid external CSS conflicts.
How it connects
Connects encapsulation to shadow DOM, light DOM, CSS, DOM queries, and event bubbling.

Also explained in

Compare how 17 books explain encapsulation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Component Development with Modern Libraries and Tooling. The section links point to the parts of the book it draws on.