On this page
  1. Shadow DOM & Web Components
  2. Contents
  3. Custom Element Lifecycle
  4. Minimal Shadow DOM Component

Shadow DOM & Web Components

Prev: Events & Delegation | Up: dom | Next: apis
Rel: Interactive & Scripting, Pseudo-Elements, Prototype Chain & new Instantiation Flow
Ref: MDN Web Docs — Using Custom Elements
Tags: #public #web #platform #dom #web-components


Contents


Custom Element Lifecycle

Custom element names must contain a hyphen (status-badge). The browser invokes four standard lifecycle callbacks:

  1. constructor() — Initialize state and attach Shadow DOM (this.attachShadow({ mode: "open" })).
  2. connectedCallback() — Called when inserted into the document.
  3. attributeChangedCallback(name, oldVal, newVal) — Called when an attribute listed in static observedAttributes changes.
  4. disconnectedCallback() — Called when removed from the document (clean up listeners/observers).

Minimal Shadow DOM Component

class StatusBadge extends HTMLElement {
  static observedAttributes = ["tone"];

  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    const span = document.createElement("span");
    span.setAttribute("part", "badge");
    const slot = document.createElement("slot");
    span.append(slot);
    this.shadowRoot.append(span);
  }

  attributeChangedCallback(name, _oldVal, newVal) {
    if (name === "tone") {
      this.shadowRoot.firstElementChild.dataset.tone = newVal ?? "neutral";
    }
  }
}

customElements.define("status-badge", StatusBadge);

Linked from

Related notes