CodeBlanks Logo Icon CodeBlanks

Custom elements

JavaScript course · Advanced · Lesson 93/100

Learn to create your own HTML element with customElements.define.

Custom elements

With custom elements you define your own HTML tags. You create a tag like <my-button> and use it like any normal HTML element. This is the foundation of design systems and component libraries.

A custom element is a class extending HTMLElement. You register it with customElements.define(name, class). The name must contain a hyphen, so the browser can tell it apart from standard tags.

Definition and lifecycle

A custom element is defined like this:

class MyAlert extends HTMLElement {
  connectedCallback() {
    this.textContent = 'Hello';
  }
}
customElements.define('my-alert', MyAlert);

The browser calls connectedCallback when the element is added to the DOM. This is the most common place for initial setup. The lifecycle callbacks are: connectedCallback (added), disconnectedCallback (removed), attributeChangedCallback (attribute changed) and adoptedCallback (moved to a new document).

These callbacks are optional; you write only the ones you need.

observedAttributes

By default attributeChangedCallback never fires. You must declare which attributes to watch with a static getter called observedAttributes:

static get observedAttributes() {
  return ['open'];
}

This is for performance; the browser calls the callback only for listed attributes, not every change. The callback takes three arguments: name, oldValue and newValue.

Exercise Define a my-toast alert element

Define a custom element named my-toast. The class should extend HTMLElement, assign a value to this.textContent inside connectedCallback, and be registered with customElements.define.

Show example solution
1. Write a MyToast class that extends HTMLElement.
2. In connectedCallback, assign a value to this.textContent.
3. Register it with customElements.define as 'my-toast'.

Example solution:
class MyToast extends HTMLElement {
  connectedCallback() {
    this.textContent = 'Sent';
  }
}
customElements.define('my-toast', MyToast);

Test yourself

  1. Why must a custom element name contain a hyphen?

    • To look nicer
    • To avoid CSS selector clashes
    • To be shorter
    • So the browser can tell it from standard tags
    Show answer

    So the browser can tell it from standard tags — Correct. The hyphen separates custom elements from standard HTML tags.

  2. Register the custom element

    customElements.define('my-alert',____);
    Show answer
    customElements.define('my-alert',MyAlert);
  3. Match lifecycle callbacks

    connectedCallback
    Added to DOM
    disconnectedCallback
    Removed from DOM
    attributeChangedCallback
    Attribute changed
    adoptedCallback
    Moved to new document

All lessons in Advanced