← Back to JavaScript, page 8

javascript-0141 · Hard senior

What are custom elements and shadow DOM, how does their lifecycle work, and how would you build a small reusable component?

Custom elements let you define your own HTML tag with a class that extends HTMLElement, registered with customElements.define, with lifecycle callbacks such as connectedCallback and attributeChangedCallback. Shadow DOM gives the component a private DOM tree with scoped styles, and slots let users place their own content inside. Together they form framework-free components that work in any page.

Full answer

Web Components are three browser standards: custom elements, shadow DOM, and templates with slots.

Custom elements: write a class that extends HTMLElement and register it with customElements.define('user-card', UserCard). The tag name must contain a hyphen. After registration, <user-card> in HTML or document.createElement('user-card') creates an instance. Elements already in the page before the definition are upgraded when it is registered.

Lifecycle callbacks:

  • constructor: runs on creation or upgrade. Call super() first, set up state and the shadow root, and do not read attributes or children or add attributes here, because they may not exist yet.
  • connectedCallback: the element was added to the document. Render and add listeners here. It can run more than once if the element is moved.
  • disconnectedCallback: it was removed. Clean up timers, global listeners, and observers.
  • attributeChangedCallback(name, oldValue, newValue): called for attributes listed in static observedAttributes, including the initial values.
  • adoptedCallback: moved to another document (rare).

Shadow DOM: this.attachShadow({ mode: 'open' }) creates a separate DOM tree. Styles inside do not leak out, and page styles do not leak in, except inherited properties and CSS custom properties, which are the intended way to theme a component. Elements inside are hidden from document.querySelector.

Slots: <slot> inside the shadow tree shows the light DOM children given by the user, and named slots (<slot name="title">) place children that have slot="title".

Communication: pass data in through attributes (strings) and properties (any value), and send data out with CustomEvent. Events that must cross the shadow boundary need composed: true, and bubbles: true to travel up.

Security: when you build HTML from attribute values, escape them or build nodes with textContent, otherwise the component is an XSS hole.

Trade-offs: no built-in templating or state updates (you write them or use a small library such as Lit), and server-side rendering support needs extra work (declarative shadow DOM). The big benefit is interoperability across frameworks.

javascript
const log = [];
const escapeHtml = (text) => text.replace(/[&<>"']/g, (ch) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[ch]));

class UserCard extends HTMLElement {
  static observedAttributes = ['name', 'role'];
  #root;

  constructor() {
    super();
    this.#root = this.attachShadow({ mode: 'open' });
    // one delegated listener on the shadow root survives re-rendering
    this.#root.addEventListener('click', (event) => {
      const button = event.target.closest('button');
      if (!button) return;
      const detail = { name: this.getAttribute('name') };
      button.dispatchEvent(new CustomEvent('select', { detail, bubbles: true, composed: true }));
      button.dispatchEvent(new CustomEvent('select-local', { detail, bubbles: true, composed: false }));
    });
    log.push('constructor');
  }

  connectedCallback() {
    log.push('connected');
    this.#render();
  }

  disconnectedCallback() {
    log.push('disconnected');
  }

  attributeChangedCallback(attribute, oldValue, newValue) {
    log.push(`attribute ${attribute}: ${oldValue} -> ${newValue}`);
    if (this.isConnected) this.#render();
  }

  #render() {
    const name = escapeHtml(this.getAttribute('name') ?? 'unknown');
    const role = escapeHtml(this.getAttribute('role') ?? 'member');
    this.#root.innerHTML = `
      <style>h2 { color: teal; } .role { font-style: italic; }</style>
      <h2>${name}</h2>
      <span class="role">${role}</span>
      <slot>no extra content</slot>
      <button>Select</button>`;
  }
}

// An element in the page before the definition is upgraded when it is registered
document.body.innerHTML = '<user-card name="Asha" role="admin"><p>Extra note</p></user-card>';
const card = document.querySelector('user-card');
log.push('defined before upgrade: ' + Boolean(customElements.get('user-card')));
customElements.define('user-card', UserCard);
log.push('defined after: ' + Boolean(customElements.get('user-card')) + ', upgraded: ' + (card instanceof UserCard));

const shadow = card.shadowRoot;
console.log(log.join('\n'));
console.log('shadow h2:', shadow.querySelector('h2').textContent, '| role:', shadow.querySelector('.role').textContent);
console.log('hidden from the page:', document.querySelector('h2'), '| in shadow:', Boolean(shadow.querySelector('h2')));
console.log('slotted nodes:', shadow.querySelector('slot').assignedNodes().map((node) => node.textContent));

log.length = 0;
card.setAttribute('name', 'Ben <script>alert(1)</script>');
console.log(log);
console.log('escaped text shown as text:', shadow.querySelector('h2').textContent, '| script elements:', shadow.querySelectorAll('script').length);

const reached = [];
document.addEventListener('select', (event) => reached.push('select from ' + event.target.localName + ' for ' + event.detail.name));
document.addEventListener('select-local', () => reached.push('select-local'));
shadow.querySelector('button').click();
console.log('events that reached the document:', reached);

log.length = 0;
const created = document.createElement('user-card');
created.setAttribute('name', 'Chen');
document.body.append(created);
created.remove();
console.log(log);

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: defined before upgrade: false constructor attribute name: null -> Asha attribute role: null -> admin connected defined after: true, upgraded: true shadow h2: Asha | role: admin hidden from the page: null | in shadow: true slotted nodes: [ 'Extra note' ] [ 'attribute name: Asha -> Ben <script>alert(1)</script>' ] escaped text shown as text: Ben <script>alert(1)</script> | script elements: 0 events that reached the document: [ 'select from user-card for Ben <script>alert(1)</script>' ] [ 'constructor', 'attribute name: null -> Chen', 'connected', 'disconnected' ]

Key points

  • Custom elements are classes extending HTMLElement, registered with a hyphenated tag name.
  • Lifecycle: constructor, connectedCallback, disconnectedCallback, attributeChangedCallback with observedAttributes.
  • Shadow DOM scopes styles and hides internals; slots project the user's children.
  • Data in through attributes and properties, out through composed CustomEvents.
  • Escape or use textContent for attribute values; consider Lit and declarative shadow DOM.

Common mistakes

  • Reading attributes or children in the constructor.
  • Building innerHTML from attribute values without escaping.
  • Forgetting composed: true so an event from inside the shadow tree stops at the shadow boundary.
  • Leaving listeners and timers running after disconnectedCallback.

Follow-ups

  • How do CSS custom properties and the part attribute let users style a shadow tree?
  • What is declarative shadow DOM and why does it matter for server rendering?
  • When would you use Lit or another library instead of plain custom elements?

Tips

  • List the lifecycle callbacks and what each is for.
  • Say that shadow DOM scopes styles and slots project user content.
  • Mention escaping and composed events.