CKTIS / JavaScript
Custom elements: observed attributes and lifecycle callbacks
Learn how a custom element chooses which attributes to observe and how it reacts to attribute writes, connection to a document, and disconnection.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
class ExampleElement extends HTMLElement {
static get observedAttributes() {
return ["data-state"];
}
attributeChangedCallback(name, oldValue, newValue, namespace) {
// React to an observed attribute.
}
connectedCallback() {
// Start work that requires a document connection.
}
disconnectedCallback() {
// Stop that work and release external resources.
}
}
customElements.define("example-element", ExampleElement);Register a class that extends HTMLElement with customElements.define(). The browser then calls lifecycle methods on instances for you. At registration it reads the static observedAttributes property if attributeChangedCallback is defined. A static getter returning an array of attribute names works; changing that array later does not update the registered list.
attributeChangedCallback(name, oldValue, newValue, namespace) responds when an observed attribute is added, set, or removed, even while the element is detached. name is the attribute’s local name, and namespace is its namespace or null. Attribute values are strings: on addition oldValue is null, and on removal newValue is null. Setting the same value can also trigger the callback. When an existing element gains its definition (an upgrade), reactions for attributes already present and observed are queued before any connection reaction for that upgrade.
connectedCallback() and disconnectedCallback() receive no arguments. They respond to connection to and disconnection from a document, respectively, including when an ancestor is inserted or removed. They can run repeatedly on the same instance; an ordinary move with insertBefore() can trigger both. Start connection-dependent listeners or timers without duplicating them, and remove those listeners or stop those timers on disconnection.
These hooks belong to the web platform, not ECMAScript 2024. Use them in a runtime with a DOM and Custom Elements support.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Custom element lifecycle demo</title>
</head>
<body>
<script>
(() => {
const log = [];
const tag = "cktis-lifecycle-demo";
class LifecycleDemo extends HTMLElement {
static get observedAttributes() {
return ["data-state"];
}
attributeChangedCallback(name, oldValue, newValue) {
log.push(`${name}: ${JSON.stringify(oldValue)} -> ${JSON.stringify(newValue)}`);
}
connectedCallback() {
log.push("connected");
}
disconnectedCallback() {
log.push("disconnected");
}
}
customElements.define(tag, LifecycleDemo);
const element = document.createElement(tag);
element.setAttribute("data-state", "idle");
document.body.append(element);
element.setAttribute("data-state", "ready");
element.setAttribute("data-note", "not observed");
element.removeAttribute("data-state");
element.remove();
document.body.append(element);
element.remove();
console.log(log.join("\n"));
})();
</script>
</body>
</html>Result
data-state: null -> "idle" connected data-state: "idle" -> "ready" data-state: "ready" -> null disconnected connected disconnected
In the browser console, the first `data-state` change appears before `connected`, and `data-note` produces no line. Removing `data-state` gives `null` as the new value, while reinsertion triggers `connected` a second time.
Related lessons
- JavaScript · Lesson 38 · Intermediate · Version: 3