Custom Elements
HTML has a fixed vocabulary, and every framework before 2018 worked around that limit the same way: render a pile of divs, give them class names that nobody else owns, and hope the styles did not collide with someone else's. Custom elements change the arrangement. You pick a tag name containing a dash, register a class against it, and the browser starts treating your component as a first-class element that parses from HTML, appears in the DOM inspector, and fires lifecycle callbacks the way a built-in element would.
The dash is not decoration. It is the registration rule that keeps the specification extensible without ever colliding with a future HTML element; usercard would eventually conflict with something the standardisation body ships, user-card never will. The same rule is why every framework-defined tag you have seen in markup, from ion-button to my-app, carries that hyphen.
What registration buys you in practice:
- markup that parses correctly before any script runs, because unknown elements still build a DOM
- a lifecycle that mirrors the element's real relationship with the document
- attribute observation driven by a declared list rather than a MutationObserver you poll
- a default style boundary through Shadow DOM, so component CSS cannot leak outward
- reuse across frameworks, since the element works identically in React, Vue, or plain files
The Lifecycle and When to Use Each Callback
Four callbacks cover almost every use, and each one maps to a concrete moment rather than a vague initialization phase. Knowing which moment you are in prevents the classic bug of re-running setup every time an attribute changes.
| Callback | Fires when | Typical responsibility | Runs more than once? |
|---|---|---|---|
constructor | The element is created, before it is in the document | Attach the shadow root, set up initial state | Once per instance |
connectedCallback | The element is inserted into a document | Start observing, fetch data, add listeners | Every time it is re-inserted |
disconnectedCallback | The element is removed from a document | Clean up timers, abort requests, remove listeners | Every time it is removed |
attributeChangedCallback | An observed attribute changes | Re-render, update derived state | Once per change, including the initial value in some cases |
adoptedCallback | The element moves to a new document | Re-bind to the new owner document | Rarely |
The rule of thumb that saves debugging time: anything that must be undone belongs in disconnectedCallback, and anything that touches external resources belongs in connectedCallback, never in the constructor. The constructor runs before the element has a parent, so querying siblings or measuring layout there throws or silently returns nothing.
A Complete User Card, Start to Finish
The element below reads three attributes, renders into a shadow root, and cleans up its own refresh timer when it leaves the document. It is deliberately framework-free: the same file works in a static page and inside a React tree.
<article>
<h2>Team</h2>
<user-card name="Ada Lovelace" role="Analyst" email="ada@example.com"></user-card>
<user-card name="Grace Hopper" role="Engineer" email="grace@example.com"></user-card>
</article>
<script>
class UserCard extends HTMLElement {
static get observedAttributes() {
return ['name', 'role', 'email'];
}
constructor() {
super();
this.attachShadow({ mode: 'open' });
this._timer = null;
}
connectedCallback() {
this.render();
this._timer = setInterval(() => this.setAttribute('data-refresh', Date.now()), 60000);
}
disconnectedCallback() {
clearInterval(this._timer);
this._timer = null;
}
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue === newValue) return;
this.render();
}
render() {
const name = this.getAttribute('name') || 'Unnamed';
const role = this.getAttribute('role') || 'Member';
const email = this.getAttribute('email') || '';
this.shadowRoot.innerHTML = `
<style>
:host { display: block; font-family: system-ui, sans-serif; }
.card {
display: flex; gap: 14px; align-items: center;
padding: 14px 16px; border: 1px solid #e2e8f0;
border-radius: 10px; background: #fff;
}
.initials {
width: 44px; height: 44px; border-radius: 50%;
display: grid; place-items: center;
background: #2563eb; color: #fff; font-weight: 700;
}
.meta strong { display: block; }
.meta span { color: #64748b; font-size: 0.9rem; }
</style>
<div class="card">
<div class="initials">${name.split(' ').map((p) => p[0]).join('')}</div>
<div class="meta">
<strong>${name}</strong>
<span>${role}${email ? ' ¡ ' + email : ''}</span>
</div>
</div>
`;
}
}
customElements.define('user-card', UserCard);
</script>
Everything inside the template string is written with textContent semantics in mind: the name comes from an attribute you control, but a production version should still escape it before interpolation if user-generated content can reach it. Setting innerHTML with untrusted values is the same cross-site scripting hole it has always been, and encapsulation does not change that.
Observing Attributes Without Repainting Everything
observedAttributes is a static getter, which means the list is fixed when the class is registered. Adding an entry later requires a new definition, because redefining an already-registered name throws. The callback then fires for each observed attribute in the order the changes happened, passing both the old and the new value, which lets you skip redundant work with a single equality check.
For attributes that change at high frequency, such as a progress value written on every animation frame, observing each one individually is wasteful. Batch the updates instead: mark the element dirty in the callback and re-render once inside a requestAnimationFrame callback. The same technique keeps a list of a thousand cards responsive while their attributes stream in.
A second pattern is worth knowing: reflecting state back out. If the component's visual state is meaningful to the outside world, mirror it into an attribute such as expanded or variant so that external stylesheets can target it and tests can assert on markup rather than on internal properties.
â ī¸Do not observe class or style
Observing class or style creates feedback loops, because rendering often writes those very attributes. If you need to react to a class change coming from outside, read it in connectedCallback and handle it through a MutationObserver with attributeFilter instead.
Shadow DOM: Encapsulation Without Secrecy
Attaching a shadow root creates a separate style scope. Selectors defined in the page do not reach inside, and selectors defined inside do not reach out, which ends the specificity arms race that component libraries fight every day. The one-way mirror has two deliberate exceptions: inherited properties such as colour and font still flow in, and the :host pseudo-element lets the component set its own outer styles.
Shadow DOM is encapsulation, not a security boundary. Anyone with the console can open a closed root through the element reference, and the content is always in the DOM for the browser to lay out. Treat it as a contract with other developers on the same page, not as protection against a hostile one.
class ToggleSwitch extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
:host { display: inline-block; }
:host([disabled]) { opacity: 0.5; pointer-events: none; }
button {
width: 52px; height: 28px; border-radius: 999px;
border: none; cursor: pointer; position: relative;
background: #cbd5e1; transition: background 160ms ease;
}
button[aria-checked="true"] { background: #16a34a; }
button::after {
content: ""; position: absolute; top: 3px; left: 3px;
width: 22px; height: 22px; border-radius: 50%;
background: #fff; transition: transform 160ms ease;
}
button[aria-checked="true"]::after { transform: translateX(24px); }
</style>
<button role="switch" aria-checked="false" type="button">
<slot></slot>
</button>
`;
}
connectedCallback() {
const button = this.shadowRoot.querySelector('button');
button.setAttribute('aria-checked', String(this.hasAttribute('checked')));
button.addEventListener('click', () => this.toggle());
}
toggle() {
if (this.hasAttribute('disabled')) return;
const next = !this.hasAttribute('checked');
next ? this.setAttribute('checked', '') : this.removeAttribute('checked');
this.shadowRoot.querySelector('button').setAttribute('aria-checked', String(next));
this.dispatchEvent(new CustomEvent('change', { bubbles: true }));
}
}
customElements.define('toggle-switch', ToggleSwitch);
The slot element is how light DOM content gets in. Text placed between the opening and closing tags of the element in the page is projected into the slot, so the caller keeps writing ordinary content while the component owns everything around it. Distributing that content into nested slots is where most component layouts get their flexibility.
Custom Elements Versus Framework Components
Both approaches solve the same problem and they are not rivals so much as different scopes of ownership.
| Dimension | Custom element | Framework component |
|---|---|---|
| Reuse across frameworks | Works anywhere HTML parses | Locked to one runtime |
| Style isolation | Shadow DOM by default | Usually requires a convention |
| Server rendering | Parses without script | Depends on the framework |
| Reactive data model | You build it with attributes and events | Provided by the framework |
| Developer ergonomics | Verbose for deeply dynamic UI | Concise, with templating |
| Interop in a micro-frontend | Native, no adapter needed | Needs a wrapper |
The pragmatic answer for a mixed codebase is to use custom elements at the boundaries where systems meet, such as an embeddable widget or a design system consumed by several apps, and to use the local framework's components for the interior of a screen where data flows are dense and the framework is already present.
Naming, Upgrades and Registration Order
A tag name must contain a dash, must be lowercase, and cannot start with the letters xml. Registration is global per document, so defining the same name twice throws; in a bundle loaded twice, guard with customElements.get(name) before defining. Elements present in the markup before their definition is executed upgrade into the class when the definition runs, which is why a component defined at the end of the body still works and why the constructor must tolerate being called without attributes already set.
Keep the class small and the public surface attribute-driven. Attributes are what the HTML author, the test suite, and the CSS on the page can all reach, and every behaviour exposed that way survives the component being used somewhere you never anticipated.
Common Mistakes
Doing document queries or layout reads inside the constructor
Fix: Move that work to connectedCallback; the element has no parent, styles, or dimensions at construction time.
Forgetting disconnectedCallback and leaking timers or listeners
Fix: Pair every subscription made on connect with an explicit teardown on disconnect, since elements are frequently moved and re-inserted.
Re-rendering the entire shadow root on every attribute change
Fix: Compare old and new values, and coalesce bursts of changes into a single requestAnimationFrame render.
Treating Shadow DOM as a security boundary
Fix: Escape any untrusted text before interpolation; encapsulation only scopes styles, it does not sanitize content.
Key Takeaways
- Custom element names must contain a dash, which is the rule that keeps them from colliding with future HTML elements.
- The constructor prepares state, connectedCallback does work that needs a document, and disconnectedCallback undoes it.
- observedAttributes is fixed at registration time, so declare the full list up front.
- Shadow DOM scopes styles in one direction and still passes inherited properties through; it is not a security barrier.
- Place custom elements at integration boundaries between frameworks, and keep the interior of a screen in whatever framework you already use.