Web Components and Custom Elements
Published by Brayan K
Web Components are a set of browser-native standards — Custom Elements, Shadow DOM, and HTML templates — that let you build reusable, encapsulated UI elements with your own HTML tags that work in any framework or plain HTML page.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
A custom element is a lifecycle, not a function called once
A registered element can connect, disconnect and reconnect. Its constructor creates internal nodes; connection callbacks attach work that depends on a document. Moving or removing an element can trigger lifecycle callbacks. Keep attachment idempotent and remove exact listeners on disconnection.
const calls = [];
class LifeCard extends HTMLElement {
constructor() { super(); calls.push("construct"); }
connectedCallback() { calls.push("connect"); }
disconnectedCallback() { calls.push("disconnect"); }
}
window.customElements.define("life-card", LifeCard);
const card = document.createElement("life-card");
document.getElementById("app").append(card);
card.remove();
document.getElementById("app").append(card);
console.log(calls.join(", "));
card.remove();
// ✅ Expected output:
// construct, connect, disconnect, connectUse a valid custom-element name containing a hyphen. Registration belongs to the document’s registry and cannot replace an existing definition. Each complete editor example runs in a fresh document; executing the same define call twice in one document is a different situation.
class OneCard extends HTMLElement {}
window.customElements.define("one-card", OneCard);
try { window.customElements.define("one-card", class extends HTMLElement {}); }
catch (error) { console.log(error.name + ": " + error.message); }
console.log(window.customElements.get("one-card") === OneCard);
// ✅ Expected output:
// NotSupportedError: Failed to execute 'define' on 'CustomElementRegistry': the name "one-card" has already been used with this registry
// trueDo not rely on attributes or children being ready in the constructor. Existing attributes can cause attributeChangedCallback before connectedCallback during upgrade. Building Reusable UI Components with Pure JS owns ordinary mount/dispose; this lesson owns the browser’s custom-element lifecycle.
Attributes are strings; boolean attributes are presence flags
const calls = [];
const element = document.createElement("upgrade-note");
element.setAttribute("level", "2");
document.getElementById("app").append(element);
class UpgradeNote extends HTMLElement {
static observedAttributes = ["level"];
constructor() { super(); calls.push("constructor"); }
attributeChangedCallback(name, oldValue, newValue) {
calls.push(name + ":" + oldValue + "->" + newValue);
}
connectedCallback() { calls.push("connected"); }
}
window.customElements.define("upgrade-note", UpgradeNote);
console.log(calls.join(", "));
element.setAttribute("level", "3");
console.log(element.getAttribute("level"), typeof element.getAttribute("level"));
element.remove();
// ✅ Expected output:
// constructor, level:null->2, connected
// 3 stringconst element = document.createElement("div");
element.setAttribute("open", "false");
console.log(element.hasAttribute("open"));
element.toggleAttribute("open", false);
console.log(element.hasAttribute("open"));
// ✅ Expected output:
// true
// falseA property is an ordinary JavaScript API; an attribute is serialized markup. They synchronize only when code implements that policy. Parse numeric attributes explicitly, choose fallback/error rules, and compare values before reflecting changes so property and attribute setters do not call each other forever. The disclosure below uses attribute presence as its source of truth.
Shadow boundaries change DOM lookup and event paths
const host = document.createElement("div");
const shadow = host.attachShadow({ mode: "open" });
const button = document.createElement("button"); button.textContent = "Inside";
const ancestor = document.createElement("section");
shadow.append(button); ancestor.append(host); document.getElementById("app").append(ancestor);
let ancestorBubbles = 0;
ancestor.addEventListener("notice", () => ancestorBubbles++);
const seen = [];
host.addEventListener("notice", event => seen.push(
String(event.target === host) + ":" + String(event.composedPath()[0] === button)
));
button.dispatchEvent(new CustomEvent("notice", { bubbles: true }));
button.dispatchEvent(new CustomEvent("notice", { bubbles: true, composed: true }));
button.dispatchEvent(new CustomEvent("notice", { composed: true }));
console.log(seen.join(", "), ancestorBubbles);
console.log(host.querySelector("button") === null, shadow.querySelector("button") === button);
ancestor.remove();
// ✅ Expected output:
// true:true, true:true 1
// true trueThe event with both flags reaches the non-capturing listener on the ordinary ancestor above the host. The composed-only event also reaches the host listener, but does not bubble to that ancestor. Outside capture listeners can observe a composed event even when it does not bubble. Outside listeners see a retargeted host, while composedPath can reveal the internal origin for an open root. Shadow DOM is encapsulation, not a security boundary. A closed root hides the host.shadowRoot accessor; it does not make secrets safe.
const host = document.createElement("div");
const child = document.createElement("span"); child.textContent = "From the caller";
host.append(child);
const shadow = host.attachShadow({ mode: "open" });
const slot = document.createElement("slot"); shadow.append(slot);
document.getElementById("app").append(host);
console.log(slot.assignedElements()[0] === child, child.parentNode === host);
console.log(shadow.querySelector("span") === null);
host.remove();
// ✅ Expected output:
// true true
// trueA template’s content is inert until cloned and inserted; clone it for each instance so nodes are not moved between instances. Shadow styles scope selectors, but inherited properties and CSS custom properties can flow through the host. A slot preserves ownership of the caller’s children; do not delete or rewrite them to implement disclosure.
Guided exercise: emit an explicit cross-boundary notification
Complete the literal hints. The first flag lets the event move to ancestors and the second permits crossing the shadow boundary.
const host = document.createElement("div");
const shadow = host.attachShadow({ mode: "open" });
const button = document.createElement("button"); shadow.append(button);
document.getElementById("app").append(host);
host.addEventListener("choice", event => console.log(event.detail.value, event.target === host));
button.dispatchEvent(new ___("choice", { // 👉 replace ___ with CustomEvent
bubbles: ___, // 👉 replace ___ with true
composed: ___, // 👉 replace ___ with true
detail: Object.freeze({ value: 7 })
}));
host.remove();
// ✅ Expected output:
// 7 trueBuild brief: a disclosure that survives reconnecting
Register lesson-disclosure. Its open attribute is a boolean presence flag and label is trimmed text with a Details fallback. Keep a native button and a slotted panel inside an open shadow root. Synchronize aria-expanded, the button label and panel.hidden whenever attributes change. Keep caller children in light DOM.
Attach the click listener once per connection and remove it on disconnection. A button activation toggles open and emits disclosure-change with frozen detail containing open; it bubbles and is composed. Programmatic attribute changes update the view without emitting a user-action event. Closing while a light-DOM child has focus moves focus to the button first.
class LessonDisclosure extends HTMLElement {
static observedAttributes = ["open", "label"];
#button; #panel; #listening = false;
#click = () => {
this.toggleAttribute("open");
this.dispatchEvent(new CustomEvent("disclosure-change", {
bubbles: true, composed: true,
detail: Object.freeze({ open: this.hasAttribute("open") })
}));
};
constructor() {
super();
const shadow = this.attachShadow({ mode: "open" });
const style = document.createElement("style");
style.textContent = ":host { display:block } button { font:inherit } [hidden] { display:none }";
this.#button = document.createElement("button");
this.#button.type = "button";
this.#button.setAttribute("aria-controls", "panel");
this.#panel = document.createElement("div");
this.#panel.id = "panel";
this.#panel.append(document.createElement("slot"));
shadow.append(style, this.#button, this.#panel);
}
connectedCallback() {
if (!this.#listening) {
this.#button.addEventListener("click", this.#click);
this.#listening = true;
}
this.#render();
}
disconnectedCallback() {
this.#button.removeEventListener("click", this.#click);
this.#listening = false;
}
attributeChangedCallback() { this.#render(); }
#render() {
const open = this.hasAttribute("open");
if (!open && this.contains(document.activeElement)) this.#button.focus();
this.#button.textContent = this.getAttribute("label")?.trim() || "Details";
this.#button.setAttribute("aria-expanded", String(open));
this.#panel.hidden = !open;
}
}
window.customElements.define("lesson-disclosure", LessonDisclosure);
const element = document.createElement("lesson-disclosure");
element.setAttribute("label", " Notes ");
const text = document.createElement("p"); text.textContent = "Caller-owned notes";
element.append(text);
const events = [];
element.addEventListener("disclosure-change", event => events.push(event.detail.open));
document.getElementById("app").append(element);
element.shadowRoot.querySelector("button").click();
element.remove(); document.getElementById("app").append(element);
element.shadowRoot.querySelector("button").click();
console.log(events.join(", "));
console.log(element.shadowRoot.querySelector("button").textContent);
console.log(element.shadowRoot.querySelector("button").getAttribute("aria-expanded"));
console.log(text.parentNode === element, element.shadowRoot.querySelector("#panel").hidden);
element.remove();
// ✅ Expected output:
// true, false
// Notes
// false
// true trueNative button semantics provide keyboard activation, but this alone does not certify every assistive-technology combination. This component is not a form-associated custom element and does not implement validation or submission through ElementInternals. Multiple instances have separate shadow roots, so internal panel IDs are scoped separately. Test reconnecting, detached attribute changes, two instances, slotted focus and event delivery before extending it.
For ordinary propagation see Events; for external DOM changes see MutationObserver (Watching the DOM). Observe only when external ownership requires it.
Practice quiz
What does this complete program print? const e=document.createElement("div");e.setAttribute("open","false");console.log(e.hasAttribute("open"));
- true
- false
- undefined
- TypeError
Answer: true. Presence is the boolean policy; the text false does not remove an attribute.
Where should connection-dependent listeners be attached and removed?
- Only in a static initializer
- In connectedCallback and disconnectedCallback with an idempotent policy
- Every time any property is read
- They never need removal
Answer: In connectedCallback and disconnectedCallback with an idempotent policy. Connection can happen repeatedly during one element lifetime.
What does this complete program print? const h=document.createElement("div");const s=h.attachShadow({mode:"open"});s.append(document.createElement("button"));console.log(h.querySelector("button")===null);
- false
- undefined
- true
- TypeError
Answer: true. Ordinary host descendant queries do not pierce its shadow root.
Which options let a custom event reach a non-capturing listener on an ordinary ancestor above the shadow host?
- Neither flag
- Only bubbles
- Only composed
- bubbles and composed
Answer: bubbles and composed. Composition crosses the shadow boundary; bubbling then reaches an ordinary ancestor above the host. Host and capture listeners have different rules.
What does this complete program print? const e=document.createElement("div");e.setAttribute("count","2");console.log(typeof e.getAttribute("count"));
- string
- number
- boolean
- object
Answer: string. Attributes serialize values as strings.
What does a slot do to the parent of an assigned light-DOM child?
- Moves it into the shadow root
- Leaves its light-DOM parent unchanged
- Clones it automatically
- Deletes it when hidden
Answer: Leaves its light-DOM parent unchanged. Distribution changes rendering without adopting the caller’s node.
What does this complete program print? const h=document.createElement("div");h.attachShadow({mode:"closed"});console.log(h.shadowRoot===null);
- false
- undefined
- true
- SecurityError
Answer: true. The closed-root accessor is hidden; this is not a secret-storage guarantee.
Why define the policy for programmatic changes and user-action events?
- Attributes cannot change after connection
- Every attribute is a boolean
- All changes must reload the page
- Consumers need to know whether a notification represents a user action
Answer: Consumers need to know whether a notification represents a user action. The disclosure updates its view for all changes but emits its action event only from button activation.
Continue this course
- Previous: Final Project Ideas
- Next: Service Workers & PWAs — Cache assets, work offline, and make installable progressive web apps
- Quick reference: JavaScript cheat sheet