Custom Elements
By the end of this lesson you will be able to register your own HTML tags correctly, choose between the two kinds of custom element, explain exactly when each lifecycle callback runs, handle elements that appear before their JavaScript loads, and build a <price-tag> element that formats rupees the Indian way.
What you should know first: Web Components Introduction, where you built a simple <rupee-price>, Component-Based HTML Development and JavaScript Classes. Here we go further into how the browser manages custom elements.
The registry: one name, one class
Every page has a custom element registry at window.customElements. It is a table that maps tag names to JavaScript classes. Think of an RTO office: each number plate is registered once, to one vehicle, and a second request for the same plate is refused.
| Method | What it does |
|---|---|
customElements.define(name, Class) | Registers a tag name with its class |
customElements.get(name) | Returns the class, or undefined if the name is not registered |
customElements.whenDefined(name) | Returns a promise that resolves once the name is defined |
customElements.upgrade(root) | Upgrades custom elements inside a tree that is not in the page yet |
Naming rules
A valid custom element name:
- starts with a lowercase ASCII letter (a to z);
- contains at least one hyphen (
-); - has no uppercase ASCII letters;
- is not one of a few reserved names from SVG and MathML, such as
font-face,color-profileandannotation-xml.
The hyphen is a promise from the HTML standard: no built-in element will ever have one, so your tag can never clash with a future version of HTML.
customElements.define("price", class extends HTMLElement {}); // SyntaxError: no hyphen
customElements.define("Price-tag", class extends HTMLElement {}); // SyntaxError: uppercase
customElements.define("font-face", class extends HTMLElement {}); // SyntaxError: reserved name
class PriceTag extends HTMLElement {}
customElements.define("price-tag", PriceTag); // works
customElements.define("price-tag", class extends HTMLElement {}); // NotSupportedError: name taken
customElements.define("cost-tag", PriceTag); // NotSupportedError: class already usedThe error names are the same in every browser; the message text differs. A script included twice is the usual cause of NotSupportedError, so libraries often guard the call with if (!customElements.get("price-tag")). Many teams also add a short project prefix, such as shop-price-tag, to avoid clashes with third-party components.
Autonomous elements and customized built-ins
There are two kinds of custom element:
| Autonomous | Customized built-in | |
|---|---|---|
| Example markup | <price-tag> | <button is="buy-button"> |
| Class extends | HTMLElement | A built-in class, such as HTMLButtonElement |
| Registered with | define("price-tag", C) | define("buy-button", C, { extends: "button" }) |
| Built-in meaning | None, you add it | Keeps the button's role, focus and keyboard behaviour |
| Browser support | All modern browsers | Chrome and Firefox; not Safari |
A customized built-in looks attractive: you keep everything a real <button> does and add your own behaviour. But WebKit, the engine behind Safari on Mac, iPhone and iPad, has said for years that it will not implement them, and its bug for this feature is closed as "won't fix". In November 2026 that is still the case, and in India every browser on iPhone uses WebKit.
So for code that must work everywhere, use autonomous elements and put real built-in elements inside them, such as a <button> inside your <buy-button>. If you meet is= in an existing project, check whether it loads a polyfill for Safari.
Lifecycle callbacks
A custom element class can define special methods that the browser calls at certain moments. They are called lifecycle callbacks. An analogy: a bank employee gets an offer letter (constructor), joins a branch (connected), gets a new designation (attribute changed), is transferred to another company's branch (adopted) and finally leaves (disconnected).
| Callback | When the browser calls it | Typical use |
|---|---|---|
constructor() | When the element is created or upgraded | Call super() first; set up private fields; attach a shadow root |
connectedCallback() | Each time the element is inserted into a document | Render, read attributes, add listeners on window or document, start timers |
disconnectedCallback() | Each time it is removed from a document | Remove those listeners, stop timers |
attributeChangedCallback(name, oldValue, newValue) | When an attribute listed in static observedAttributes is added, changed or removed | Update the display |
adoptedCallback() | When the element is moved into a different document with adoptNode() | Rarely needed |
Three rules beginners miss:
- The constructor must not read or add attributes or children. When code calls
document.createElement("price-tag"), the element has no attributes yet. If your constructor adds one, the browser reports an error and returns a brokenHTMLUnknownElementinstead. Do that work inconnectedCallback(). connectedCallback()can run many times. Moving an element to another parent removes it and inserts it again, so you getdisconnectedCallback()thenconnectedCallback(). Guard one-time setup with a flag.- Only listed attributes are watched. Changing an attribute that is not in
observedAttributescalls nothing.
Step 1: watch the lifecycle happen
This element writes a line to the log from every callback. Click the buttons in order and read the log.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Lifecycle log</title>
<style>
.box { border: 2px dashed #90a4ae; padding: 8px; margin: 6px 0; min-height: 24px; }
life-log { display: inline-block; padding: 2px 8px; border-radius: 4px; background: #e3f2fd; }
life-log[theme="festival"] { background: #ffe082; }
</style>
</head>
<body>
<button id="add">1. Add to box A</button>
<button id="theme">2. Change theme</button>
<button id="move">3. Move to box B</button>
<button id="adopt">4. Send to another document and back</button>
<button id="remove">5. Remove</button>
<div class="box" id="a">Box A: </div>
<div class="box" id="b">Box B: </div>
<ol id="log"></ol>
<script>
function log(text) {
const li = document.createElement("li");
li.textContent = text;
document.querySelector("#log").append(li);
}
class LifeLog extends HTMLElement {
static observedAttributes = ["theme"];
constructor() { super(); log("constructor"); }
connectedCallback() {
log("connectedCallback (parent: " + (this.parentElement.id || this.parentElement.localName) + ")");
this.textContent = "life-log";
}
disconnectedCallback() { log("disconnectedCallback"); }
attributeChangedCallback(name, oldValue, newValue) {
log(`attributeChangedCallback: ${name} ${oldValue} -> ${newValue}`);
}
adoptedCallback() { log("adoptedCallback"); }
}
customElements.define("life-log", LifeLog);
let el;
document.querySelector("#add").onclick = () => {
el = document.createElement("life-log");
document.querySelector("#a").append(el);
};
document.querySelector("#theme").onclick = () => el.setAttribute("theme", "festival");
document.querySelector("#move").onclick = () => document.querySelector("#b").append(el);
document.querySelector("#adopt").onclick = () => {
const other = document.implementation.createHTMLDocument("other");
other.body.append(other.adoptNode(el));
document.querySelector("#b").append(document.adoptNode(el));
};
document.querySelector("#remove").onclick = () => el.remove();
</script>
</body>
</html>After button 1 you see "constructor" and "connectedCallback (parent: a)". Button 2 logs "theme null -> festival" and the element turns yellow. Button 3 logs "disconnectedCallback" then "connectedCallback (parent: b)": a move is a removal plus an insertion. Button 4 logs disconnected, adopted, connected twice: once into the other document (parent: body), once back into box B. Button 5 logs one last "disconnectedCallback".
Upgrades and the :defined pseudo-class
The browser does not wait for your script. If it parses <price-tag amount="499"> before define() runs, it creates a plain, unknown element and keeps going. Such an element is undefined. When define() finally runs, the browser upgrades every matching element already in the page: it runs the constructor, then attributeChangedCallback() once for each observed attribute already present, then connectedCallback().
This means your code must work whether the element existed before or after the definition. It also gives you two tools:
- The CSS pseudo-class
:definedmatches built-in elements and custom elements that are registered.price-tag:not(:defined)lets you style the waiting state, for example a grey placeholder, so the layout does not jump. await customElements.whenDefined("price-tag")lets other code wait until the class is ready.
One trap: if code sets a property on an element before it is upgraded, such as tag.amount = 999, that value is stored on the object itself and hides your class's setter. A common fix runs in connectedCallback():
if (Object.hasOwn(this, "amount")) {
const value = this.amount;
delete this.amount; // remove the early property
this.amount = value; // now the class setter runs
}Step 2: a price-tag element in rupees
Now build a <price-tag> for a Lucknow electronics shop. It has two observed attributes, amount and mrp. It formats them with Intl.NumberFormat("en-IN"), which groups digits the Indian way (₹1,29,900, not ₹129,900), and shows the discount. An amount property reflects the attribute: reading or writing the property reads or writes the attribute, like built-in elements do (see HTML Attribute Reflection). The definition is delayed by 1.5 seconds so you can watch the upgrade.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>price-tag element</title>
<style>
price-tag { display: inline-block; min-width: 9rem; }
price-tag:not(:defined) { background: #eee; color: #777; border-radius: 4px; }
price-tag:not(:defined)::before { content: "Loading price"; }
price-tag s { color: #757575; margin-inline-start: 6px; }
price-tag .off { color: #2e7d32; margin-inline-start: 6px; }
</style>
</head>
<body>
<h1>Lucknow Electronics</h1>
<p>Laptop: <price-tag id="laptop" amount="129900" mrp="149900"></price-tag></p>
<p>Earphones: <price-tag amount="1499"></price-tag></p>
<button id="sale">Festival sale: 10% off the laptop</button>
<p id="status">Waiting for the definition...</p>
<script>
const rupees = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR", maximumFractionDigits: 0 });
class PriceTag extends HTMLElement {
static observedAttributes = ["amount", "mrp"];
get amount() { return Number(this.getAttribute("amount")); }
set amount(value) { this.setAttribute("amount", value); } // reflects to the attribute
connectedCallback() { this.render(); }
attributeChangedCallback() { if (this.isConnected) this.render(); }
render() {
const amount = this.amount;
const mrp = Number(this.getAttribute("mrp"));
const price = document.createElement("data");
price.value = amount;
price.textContent = rupees.format(amount);
const parts = [price];
if (mrp > amount) {
const old = document.createElement("s");
old.textContent = "MRP " + rupees.format(mrp);
const off = document.createElement("span");
off.className = "off";
off.textContent = Math.round((1 - amount / mrp) * 100) + "% off";
parts.push(old, off);
}
this.replaceChildren(...parts);
}
}
setTimeout(() => customElements.define("price-tag", PriceTag), 1500);
customElements.whenDefined("price-tag").then(() => {
document.querySelector("#status").textContent = "price-tag is defined. Both tags were upgraded.";
});
document.querySelector("#sale").addEventListener("click", async () => {
await customElements.whenDefined("price-tag");
const laptop = document.querySelector("#laptop");
laptop.amount = Math.round(laptop.amount * 0.9);
});
</script>
</body>
</html>For 1.5 seconds you see two grey "Loading price" boxes styled by :not(:defined). Then both upgrade: the laptop shows "₹1,29,900 MRP ₹1,49,900 13% off" and the earphones show "₹1,499". Click the sale button: the property setter changes the attribute, attributeChangedCallback() runs, and the laptop shows "₹1,16,910 MRP ₹1,49,900 22% off". Open DevTools and you will see the new amount value in the HTML too. The <data> element keeps the plain number in its value attribute for scripts and search engines.
Common mistakes
- Doing setup in the constructor. Attributes and children may not exist yet; use
connectedCallback(). - Forgetting
observedAttributes. Without it,attributeChangedCallback()never runs. - Never cleaning up. A timer or
windowlistener started inconnectedCallback()keeps running after removal unlessdisconnectedCallback()stops it. - Relying on
is=for public sites. Safari ignores customized built-ins. - Assuming the element is defined. Style
:not(:defined)and usewhenDefined()where order matters.
Interview questions
1. What are the rules for a custom element name?
It must start with a lowercase ASCII letter, contain a hyphen, contain no uppercase ASCII letters and not be one of the reserved SVG and MathML names. The hyphen guarantees it never clashes with a future built-in element. An invalid name makes define() throw a SyntaxError.
2. What is the difference between autonomous custom elements and customized built-ins?
An autonomous element extends HTMLElement and is used as its own tag, such as <price-tag>. A customized built-in extends a built-in class and is used with is= on that element, keeping its native behaviour. Safari does not support customized built-ins, so autonomous elements are the cross-browser choice.
3. Explain the custom element lifecycle callbacks.
connectedCallback() runs on each insertion into a document and disconnectedCallback() on each removal. attributeChangedCallback() runs when an attribute listed in observedAttributes changes, and adoptedCallback() when adoptNode() moves the element to another document. The constructor runs at creation or upgrade and should only do light setup.
4. What is an upgrade?
When the browser parses a custom tag before its class is defined, it creates an undefined element. Calling define() later upgrades it: the constructor runs, then attributeChangedCallback() for existing observed attributes, then connectedCallback(). The :defined pseudo-class and whenDefined() help handle the waiting period.
5. Why should you not add attributes or children in the constructor?
document.createElement() expects a new element with no attributes and no children. If the constructor adds them, the browser reports an error and gives back an HTMLUnknownElement instead of your element. Rendering belongs in connectedCallback().
Key points
customElementsmaps each valid, hyphenated name to one class; a repeated name or class throwsNotSupportedError.- Use autonomous elements with real built-ins inside; customized built-ins (
is=) do not work in Safari. connectedCallback()anddisconnectedCallback()can run many times; set up and clean up in pairs.attributeChangedCallback()only fires for names instatic observedAttributes.- Elements parsed before
define()are upgraded later; style them with:not(:defined)and wait withwhenDefined(). - Reflect important attributes as properties, and format rupees with
Intl.NumberFormat("en-IN").
Exercise
Build a <sale-countdown> element for a Kochi saree shop's flash sale. It reads a seconds attribute and shows "Sale ends in 1:05", counting down every second with setInterval() started in connectedCallback(). At zero it shows "Sale over". It must stop its timer in disconnectedCallback(), and changing seconds must restart the count. Add a button that removes the element and a line of text that proves the timer stopped (for example, a counter of ticks that stops increasing).
Show solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sale countdown</title>
</head>
<body>
<h1>Kochi Silks flash sale</h1>
<p><sale-countdown id="timer" seconds="65"></sale-countdown></p>
<button id="remove">Remove timer</button>
<button id="extend">Extend to 2 minutes</button>
<p>Ticks so far: <span id="ticks">0</span></p>
<script>
let ticks = 0;
class SaleCountdown extends HTMLElement {
static observedAttributes = ["seconds"];
#left = 0;
#timer = null;
connectedCallback() { this.#start(); }
disconnectedCallback() { clearInterval(this.#timer); }
attributeChangedCallback() { if (this.isConnected) this.#start(); }
#start() {
clearInterval(this.#timer);
this.#left = Math.max(0, Number(this.getAttribute("seconds")) || 0);
this.#show();
this.#timer = setInterval(() => {
ticks++;
document.querySelector("#ticks").textContent = ticks;
this.#left--;
this.#show();
if (this.#left <= 0) clearInterval(this.#timer);
}, 1000);
}
#show() {
const m = Math.floor(this.#left / 60);
const s = String(this.#left % 60).padStart(2, "0");
this.textContent = this.#left > 0 ? `Sale ends in ${m}:${s}` : "Sale over";
}
}
customElements.define("sale-countdown", SaleCountdown);
document.querySelector("#remove").onclick = () => document.querySelector("#timer")?.remove();
document.querySelector("#extend").onclick = () => document.querySelector("#timer")?.setAttribute("seconds", "120");
</script>
</body>
</html>The timer starts on insertion and is cleared on removal, so the tick counter freezes after "Remove timer". Changing seconds calls attributeChangedCallback(), which clears the old interval before starting a new one, so two timers never run at once.
Quick Quiz
1. Which name can be passed to customElements.define()?
Names need a hyphen and no uppercase letters, and font-face is reserved.
2. An element is moved from one <div> to another on the same page. Which callbacks run?
A move is a removal followed by an insertion.
3. Why is <button is="buy-button"> risky on a public website?
WebKit has declined to implement customized built-ins, so the extra behaviour is missing in Safari.
4. What does price-tag:not(:defined) select?
:defined matches registered custom elements; the negation styles the waiting state before the upgrade.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
