Custom Elements With Lifecycle Callbacks
Register a custom element and use connectedCallback and attributeChangedCallback to render content and react to attribute updates.
Code
class StatusBadge extends HTMLElement {
static observedAttributes = ['status'];
connectedCallback() {
this.render();
console.log('connected:', this.getAttribute('status'));
}
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue !== newValue) {
console.log('attribute changed:', name, oldValue, '->', newValue);
this.render();
}
}
render() {
const status = this.getAttribute('status') ?? 'unknown';
this.textContent = status.toUpperCase();
}
}
customElements.define('status-badge', StatusBadge);
const badge = document.createElement('status-badge');
badge.setAttribute('status', 'ready');
document.body.append(badge);
badge.setAttribute('status', 'done');
console.log('rendered text:', badge.textContent);How the snippet works
Custom Elements With Lifecycle Callbacks keeps everything in the class StatusBadge.
Everything operates on top-level bindings: badge.
Caveats
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide.
Applying it
Look for the connected:, attribute changed:, rendered text: prefixes when the file runs; they tie each line to its step.
Statements that matter
const status = this.getAttribute('status') ?? 'unknown';
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does Custom Elements With Lifecycle Callbacks run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.