0Pricing
HTML Academy · Lesson

attachShadow and Shadow Root

Create an encapsulated shadow tree on a host element.

What is Shadow DOM?

Shadow DOM gives an element its own isolated DOM tree (the "shadow tree") that does not appear in the page's main DOM. Outer CSS does not leak in, inner CSS does not leak out — perfect encapsulation for components.

Attaching a Shadow Root

Call this.attachShadow({ mode: "open" }) from a custom element's constructor or connectedCallback. The method returns a ShadowRoot, which you can populate just like a regular DOM tree using innerHTML, appendChild, etc.

class MyCard extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({ mode: "open" });
    shadow.innerHTML = "<style>p{color:red}</style><p>Hello</p>";
  }
}

All lessons in this course

  1. attachShadow and Shadow Root
  2. Slot Elements for Content Distribution
  3. Scoped Styles Inside Shadow DOM
  4. Part and Exportparts for External Styling
← Back to HTML Academy