Custom Elements With Lifecycle Callbacks

Register a custom element and use connectedCallback and attributeChangedCallback to render content and react to attribute updates.

JavascriptData Integrity

Code

javascriptsnippet
28 lines
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

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.