← Back to HTML & CSS, page 6

html-css-0113 · Hard senior

How do you define a custom element, and when do its lifecycle callbacks run?

Extend HTMLElement and register the class with customElements.define using a name with a dash. The browser calls constructor, connectedCallback, disconnectedCallback and attributeChangedCallback for observed attributes. Keep the constructor light, set up in connectedCallback and clean up in disconnectedCallback.

Full answer

A custom element is your own HTML tag backed by a JavaScript class. The class extends HTMLElement, and you register it with customElements.define("name-here", Class). The name must contain a dash, such as course-badge, so it cannot clash with future built-in tags.

The browser calls these methods:

  • constructor: when an element is created. Call super() first. Do not read attributes or add children here, because an element made by the parser may not have them yet. Keep it light.
  • connectedCallback: each time the element is added to a document. Set up content and event listeners here. It can run more than once if the element is moved.
  • disconnectedCallback: when it is removed. Clean up timers and listeners.
  • attributeChangedCallback(name, oldValue, newValue): when an attribute listed in the static observedAttributes array changes. It also runs for the attributes present at the start, before connectedCallback.
  • adoptedCallback: when it moves to a new document, which is rare.

Good practice: keep the attribute as the source of truth for simple values, expose a matching property, and make setup safe to run twice. Because the tag may be in the HTML before the class is defined, the element is first an unknown element and is upgraded when define runs. customElements.whenDefined() returns a promise for that moment.

The result is progressive: if the script fails, the content inside the tag is still in the page.

When the class is defined, the element in the page is upgraded. The log shows the attribute call first, with the value null to easy, and then connected. After changing level to hard, the log gets a new entry and the label updates. Removing the element adds disconnected.

The element is defined after it appears in the HTML, which is common, so test both orders.

html
<course-badge id="b" level="easy">HTML</course-badge>
<script>
  window.log = [];
  class CourseBadge extends HTMLElement {
    static observedAttributes = ["level"];
    connectedCallback() { log.push("connected"); this.render(); }
    disconnectedCallback() { log.push("disconnected"); }
    attributeChangedCallback(name, oldV, newV) { log.push(name + ":" + oldV + ">" + newV); if (this.isConnected) this.render(); }
    render() { this.dataset.label = this.textContent.split(" (")[0] + " (" + this.getAttribute("level") + ")"; }
  }
  customElements.define("course-badge", CourseBadge);
</script>

Checked in Chrome 156 only. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • Names must contain a dash.
  • constructor should be light; no attributes or children.
  • connectedCallback and disconnectedCallback run on add and remove.
  • attributeChangedCallback needs observedAttributes.
  • Elements already in the HTML are upgraded on define.

Common mistakes

  • Reading attributes or adding children in the constructor.
  • Forgetting to list attributes in observedAttributes, so changes are ignored.
  • Adding listeners in connectedCallback and never removing them, so moving the element adds them twice.

Follow-ups

  • Why must a custom element name contain a dash?
  • What does upgrading mean?

Tips

  • Walk through the order of calls for an element that is upgraded.
  • Mention that connectedCallback may run more than once.