Custom Elements Observe Typed Attributes
customElements.define with observedAttributes turns HTML attributes into a typed config surface, and an HTMLElementTagNameMap entry types createElement calls.
Code
// Custom Elements: observedAttributes declares the config keys the component watches (its configuration surface),
// attributeChangedCallback reacts to each change
class UserBadge extends HTMLElement {
static observedAttributes = ['name', 'role'];
private displayRole = 'guest';
connectedCallback(): void {
this.render();
}
attributeChangedCallback(name: string, _oldValue: string | null, next: string | null): void {
if (name === 'role') this.displayRole = next ?? 'guest';
if (name === 'name') this.render();
}
private render(): void {
this.textContent = `${this.getAttribute('name') ?? 'anon'} · ${this.displayRole}`;
}
}
customElements.define('user-badge', UserBadge);
// Declaration merging makes querySelector/createElement('user-badge') return UserBadge directly
declare global {
interface HTMLElementTagNameMap {
'user-badge': UserBadge;
}
}
export {};
const badge = document.createElement('user-badge');
badge.setAttribute('name', 'Ada');
badge.setAttribute('role', 'admin');
document.body.append(badge);
console.log('badge renders:', badge.textContent);Inside the snippet
Custom Elements Observe Typed Attributes is built around the class UserBadge.
Module-level bindings hold the data — badge — with no function scope in between.
What to watch for
- A browser is the runtime here:
documentare not available in Node.
Putting it to use
Running the file prints labeled results such as badge renders: — each operation’s effect is visible in the output.
Core lines
this.textContent = `${this.getAttribute('name') ?? 'anon'} · ${this.displayRole}`;
if (name === 'role') this.displayRole = next ?? 'guest';
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.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.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- Does Custom Elements Observe Typed Attributes 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.