Web Components: Custom Elements, Shadow DOM, Templates and Slots
Build reusable HTML elements with no framework: defining custom elements, lifecycle callbacks and observedAttributes, upgrades and :defined, shadow DOM encapsulation, :host, ::slotted and ::part, slots, event retargeting, declarative shadow DOM and form-associated elements.
kvi5hnuCode Sprout team member9 min readOn this page
Frameworks like React and Vue let you package markup, styles and behavior into reusable components. Web components are the browser's built-in way to do the same: you define a new HTML tag, such as <rating-stars>, and it works in plain HTML, with any framework, or with none. Three standards make this possible:
- Custom elements associate a JavaScript class with a tag name.
- Shadow DOM gives the element a private DOM tree and styles that the page can't accidentally break.
- Templates (
<template>, from article 110) hold inert markup to clone efficiently.
The behaviors described in this article were verified by running the example code.
Using a web component
To someone using a component, it looks like any other tag. Load its definition, usually a module, and write the tag:
<script type="module" src="/components/rating-stars.js"></script>
<rating-stars value="3" max="5"></rating-stars>
<search-field placeholder="Find tea">
<span slot="icon">🔍</span>
</search-field>
Rules and behaviors to know:
- Custom tag names must contain a hyphen (
rating-stars,x-tabs), so they never clash with future standard elements. - They always need a closing tag:
<rating-stars />is not self-closing in HTML. - Some components accept children in named slots (
slot="icon"above). The component's documentation says which slots and attributes it supports.
Because module scripts run after the HTML is parsed, the browser meets <rating-stars> before it knows what it is. It creates a plain HTMLElement and upgrades it into the real class once the definition runs. Until then, the element matches the :not(:defined) selector, which you can use to avoid a flash of unstyled content:
rating-stars:not(:defined) {
display: inline-block;
width: 7.5rem; /* reserve roughly the final size so the layout doesn't jump */
visibility: hidden;
}
In JavaScript, await customElements.whenDefined("rating-stars") waits for the definition before you use the element's properties and methods.
Defining a custom element
A custom element is a class that extends HTMLElement, registered with customElements.define(name, class):
class RatingStars extends HTMLElement {
static observedAttributes = ["value", "max"];
#root;
constructor() {
super(); // always first
this.#root = this.attachShadow({ mode: "open" });
}
connectedCallback() { // inserted into a document
this.#render();
}
attributeChangedCallback(name, oldValue, newValue) {
if (this.isConnected) this.#render();
}
get value() { return Number(this.getAttribute("value") ?? 0); }
set value(v) { this.setAttribute("value", String(v)); }
get max() { return Number(this.getAttribute("max") ?? 5); }
#render() {
const stars = Array.from({ length: this.max }, (_, i) => {
const filled = i < this.value;
return `<button part="star" data-n="${i + 1}" aria-pressed="${filled}">${filled ? "★" : "☆"}</button>`;
});
this.#root.innerHTML = `<style>button { border: 0; background: none; font-size: 1.5em; }</style>${stars.join("")}`;
}
}
customElements.define("rating-stars", RatingStars);
The rendered markup is built from numbers the component controls, not from user text, so innerHTML is safe here (article 110).
Lifecycle callbacks
The browser calls these methods automatically:
| Callback | When it runs |
|---|---|
constructor() | the element is created or upgraded. Call super() first; set up internal state and the shadow root, but don't read attributes or children or add attributes here |
connectedCallback() | the element is inserted into a document, and again every time it's moved |
disconnectedCallback() | it's removed from the document. Clean up timers, observers and global listeners here |
attributeChangedCallback(name, old, new) | an attribute listed in static observedAttributes is added, changed or removed |
adoptedCallback() | it's moved into a different document (rare) |
For the markup <rating-stars value="3" max="5">, the upgrade produces this sequence: constructor, then attr value: null -> 3, attr max: null -> 5, then connected. Initial attributes trigger attributeChangedCallback before connectedCallback, which is why the example checks isConnected before rendering. Setting stars.value = 4 calls the setter, which sets the attribute, which triggers attributeChangedCallback and re-renders. Moving the element with remove() and append() runs disconnected, then connected.
The property–attribute pattern shown here mirrors built-in elements: attributes (strings, set in HTML) and properties (typed, set from JavaScript) stay in sync, with the attribute as the single source of truth.
Other registry details:
document.createElement("rating-stars")creates a fully upgraded instance immediately.- Defining the same name twice throws a
NotSupportedError, and a name without a hyphen throws aSyntaxError. customElements.get(name)returns the class, andwhenDefined(name)returns a promise.- Always extend
HTMLElement. "Customized built-ins" (class extends HTMLButtonElementwith<button is="...">) are not supported in Safari.
Shadow DOM: encapsulation
The first version of a component might set styles and children directly on itself. That's fragile: page CSS can restyle its internals, document.querySelectorAll("button") would find its private buttons, and the page's own code can break it. A shadow root solves this by giving the element a separate, private DOM tree:
const root = this.attachShadow({ mode: "open" }); // also sets this.shadowRoot
root.innerHTML = "..."; // or root.append(...)

The element that owns the shadow root is the shadow host. Its regular children are called the light DOM. The boundary between them works like this:
- DOM queries stop at the boundary.
document.querySelectorAll("button")finds none of the component's internal buttons; you have to go throughelement.shadowRoot.querySelector(...). Withmode: "closed",shadowRootreturnsnull, but this is a weak barrier (the component can still keep its own reference), and most components use"open". - Styles are scoped both ways. A
<style>inside the shadow root applies only there, so simple selectors likebuttonare safe. Page styles don't apply inside, except for inherited properties (color,font, etc.) and custom properties, which deliberately pass through and are the intended way to theme a component. - Built-in elements use it too. The controls of
<video>and<input type="range">are browser-internal shadow trees, which is why you can't style their parts with ordinary selectors.
Besides custom elements, attachShadow works on a set of standard elements, including <div>, <span>, <article>, <section> and <p>.
Styling a component from inside and outside
Inside the shadow root:
:host { display: inline-flex; gap: 0.25rem; } /* the host element itself */
:host([disabled]) { opacity: 0.5; } /* host with an attribute */
:host(:focus-within) { outline: 2px solid var(--focus-color, royalblue); }
::slotted(img) { width: 1.25em; } /* slotted light-DOM children (top level only) */
button { color: var(--star-color, goldenrod); } /* themable via a custom property */
From the page:
rating-stars { --star-color: crimson; } /* custom properties pass through */
rating-stars::part(star) { padding: 0.1em; } /* elements marked part="star" */
part="..." attributes let a component expose specific internals for external styling, while everything else stays private. :host styles have lower priority than the page's styles for the same element, so users can always override the component's defaults on the host.
Instead of a <style> element in each instance, components can share one constructable stylesheet: this.shadowRoot.adoptedStyleSheets = [sheet] (article 111).
Slots: composing with light DOM children
A <slot> in the shadow tree is a placeholder where the host's light DOM children are rendered. Children with slot="name" go to <slot name="name">, and everything else goes to the unnamed default slot. Content inside a <slot> element is fallback content, shown when nothing is assigned:
const template = document.createElement("template");
template.innerHTML = `
<style>:host { display: inline-flex; align-items: center; border: 1px solid #94a3b8; border-radius: 0.5rem; }</style>
<slot name="icon">🔎</slot>
<input type="search">
<slot></slot>
`;
class SearchField extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" }).append(template.content.cloneNode(true));
this.input = this.shadowRoot.querySelector("input");
}
connectedCallback() {
this.input.placeholder = this.getAttribute("placeholder") ?? "";
}
}
customElements.define("search-field", SearchField);
Creating the template once, outside the class, means the HTML is parsed only once, and each instance just clones it.
Slotted nodes stay in the light DOM: they're still children of the host, they're styled by the page's CSS, and the page's queries find them. Only their rendering location changes. From inside, slot.assignedElements() lists what was slotted (here, the <span> for the icon slot), and the slotchange event fires on a slot when its assigned content changes.
Events across the boundary
Events from inside a shadow tree are retargeted: listeners outside see event.target as the host element, not the internal <input> or <button>, which keeps the internals private. event.composedPath() reveals the full path for open roots.
A component communicates with the page by dispatching its own events. To make an event escape the shadow root and bubble through the page, set both bubbles and composed:
this.input.addEventListener("change", () => {
this.dispatchEvent(new CustomEvent("search", {
detail: this.input.value,
bubbles: true,
composed: true,
}));
});
document.addEventListener("search", (event) => {
console.log(event.target.tagName, event.detail); // "SEARCH-FIELD" "oolong"
});
Most UI events (click, input, keydown) are already composed. change and custom events are not, unless you say so. Here, the event is dispatched on the host itself, so it bubbles through the page anyway; composed matters when you dispatch from an element inside the shadow tree.
Declarative shadow DOM
A shadow root can also be written directly in HTML, so server-rendered pages show styled components before any JavaScript loads:
<rating-stars value="3">
<template shadowrootmode="open">
<style>button { border: 0; background: none; }</style>
<button part="star">★</button><button part="star">★</button><button part="star">★</button>
</template>
</rating-stars>
The parser attaches the shadow root and removes the <template>. When the class is defined later, the constructor should check this.shadowRoot and reuse the existing root instead of calling attachShadow again. Declarative shadow DOM has been supported in all major browsers since 2024.
Form-associated custom elements
By default, a custom input isn't part of its <form>: its value isn't submitted, and it doesn't participate in validation or reset. Setting static formAssociated = true and calling this.attachInternals() gives the element an ElementInternals object that connects it to forms:
class RatingInput extends RatingStars {
static formAssociated = true;
#internals = this.attachInternals();
set value(v) {
super.value = v;
this.#internals.setFormValue(String(v)); // submitted with the form's data
this.#internals.setValidity(v > 0 ? {} : { valueMissing: true }, "Please pick a rating");
}
get value() { return super.value; }
}
customElements.define("rating-input", RatingInput);
Such elements work with <label>, form.elements, FormData, required-style validation and form reset (formResetCallback). ElementInternals can also set default ARIA roles and states (internals.role = "slider") without adding attributes on the host.
When to use web components
Web components are a good fit for design systems and widgets shared across teams that use different frameworks, embeddable widgets for other people's sites, and progressively enhanced pages. Writing them by hand involves a lot of plumbing (rendering, attribute reflection, accessibility), so many teams use a small library such as Lit, which adds reactive properties and efficient templating on top of these standards. Whichever you choose, accessibility is your responsibility: use real <button>s and <input>s inside, manage focus, and set ARIA states.
Common questions
Why can't I read attributes in the constructor?
When an element is created with document.createElement, it has no attributes or children yet during construction, and the specification forbids adding them there. Read them in connectedCallback or attributeChangedCallback.
Why doesn't my page CSS style the component's internals?
Shadow DOM scopes styles. Theme components through custom properties (--star-color), inherited properties, or ::part() for exposed parts. That's the intended design.
Is mode: "closed" a security feature?
No. It only hides the shadowRoot property. Code running in the same page can still interfere with the component in other ways. Use "open" unless you have a specific reason not to.
Do I need a shadow root to make a custom element?
No. Custom elements without shadow DOM are fine for behavior-only enhancements (for example, wrapping existing light-DOM markup). Shadow DOM is for encapsulating the component's own markup and styles.
Summary
customElements.define("name-with-hyphen", class extends HTMLElement {...})creates a new tag; existing elements are upgraded, and:definedandwhenDefined()track definitions.- Lifecycle callbacks:
constructor(callsuper()first),connectedCallback,disconnectedCallback, andattributeChangedCallbackfor attributes listed instatic observedAttributes. attachShadow({ mode: "open" })creates an encapsulated tree: queries and page styles stop at the boundary, except inherited and custom properties.- Style with
:host,::slotted()andpart/::part(); compose with named and default<slot>s, which render light-DOM children without moving them. - Events are retargeted to the host; use
bubbles: true, composed: truefor custom events that must leave the shadow tree. <template shadowrootmode="open">renders components from HTML alone, andstatic formAssociatedwithattachInternals()makes custom inputs work with forms.
Practice Questions
Why does customElements.define("datepicker", DatePicker) throw?
Answer
Custom element names must contain a hyphen, so this throws a SyntaxError. Use a name like date-picker.
A component lists static observedAttributes = ["open"]. Which callback runs when the page does el.setAttribute("open", ""), and with which arguments?
Answer
attributeChangedCallback("open", null, ""), assuming the attribute wasn't present before. Unlisted attributes don't trigger the callback.
The page's CSS says button { color: red }. Are the buttons inside a component's shadow root red?
Answer
No. Page selectors don't match elements inside shadow trees. Only inherited properties and custom properties pass through, so a component that wants to be themable can use color: var(--button-color, inherit).
A component dispatches new CustomEvent("select", { bubbles: true }) from a button inside its shadow root. A listener on document never fires. Why?
Answer
The event isn't composed, so it stops at the shadow root. Add composed: true, or dispatch the event on the host element itself (this.dispatchEvent(...)).
Next: Scripting SVG: Inline Vector Graphics, createElementNS, Paths and a Data-Driven Pie Chart

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.