On this page
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:
constructor()— Initialize state and attach Shadow DOM (this.attachShadow({ mode: "open" })).connectedCallback()— Called when inserted into the document.attributeChangedCallback(name, oldVal, newVal)— Called when an attribute listed instatic observedAttributeschanges.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
- tuts/web/dom Linked here; links to this page; shared tags: #dom, #platform, #web
- tuts/web/dom/events_and_delegation Linked here; links to this page; shared tags: #dom, #platform, #web
- tuts/css/selectors/pseudo_elements Linked here; links to this page; shared tags: #web
- tuts/html/elements/interactive_and_scripting Linked here; links to this page; shared tags: #web
- tuts/web/apis Linked here; shared tags: #platform, #web
- tuts/javascript/tutorials/prototype_chain_and_new_flow Linked here; shared tags: #web
- tuts/web/dom/nodes_and_elements shared tags: #dom, #platform, #web
- tuts/web shared tags: #platform, #web
- tuts/web/apis/fetch_and_networking shared tags: #platform, #web
- tuts/web/apis/observers_and_workers shared tags: #platform, #web