liveBook · Manning

Custom Elements

As explained in Vanilla Web

A developer-defined HTML element registered through the browser's custom element APIs with custom behavior and lifecycle callbacks.

When the same interface behavior appears across pages, a custom element can give it a reusable HTML tag. Define a class, register it with the browser, and each matching tag becomes an instance with its own behavior. Custom Elements are the entry point to Web Components, not a complete encapsulation system: Shadow DOM, templates, and other APIs are separate choices. section 7.1 section 7.5

To create an autonomous custom element:

  • Extend HTMLElement. Call super() in the constructor and initialize state there; do not assume attributes or child nodes have been parsed. section 7.6.1
  • Use connectedCallback() when the element enters the document to read attributes, build content, and attach listeners. Account for it running again if the element moves. section 7.6.1 section 7.7
  • Register the class with customElements.define('my-widget', MyWidget). Names require a hyphen and cannot be registered twice. In HTML, write an explicit closing tag. section 7.6.3

Independent counter buttons

A <counter-button> can create a button on connection, increment private state on clicks, and update its label. Three tags produce three independent counters. A check for an existing button prevents a second button and listener when a counter reconnects. section 7.7

Listing 7.2 A CounterButton web component
class CounterButton extends HTMLElement {
    #count; #1

    constructor() {
        super();
        this.#count = 0; #2
    }
    connectedCallback() {
        if (this.querySelector('button')) return; #3
        const button = document.createElement('button');
        button.textContent = 'Clicks: 0';
        button.addEventListener('click', () => {
            this.#count++; #4
            button.textContent = `Clicks: ${this.#count}`;
        });
        this.appendChild(button);
    }
}

customElements.define('counter-button', CounterButton);

The counter implementation shows registration, per-instance state, and a guard against repeating connectedCallback() setup. section 7.7

Keep the public contract small. Attributes provide declarative string values; JavaScript properties can carry complex values. Methods can expose actions, and DOM events report changes to consumers. CSS custom properties can make appearance configurable. These interfaces let a page use the tag without depending on its internal nodes. section 7.9 section 7.5.1

Choose whether the element needs Shadow DOM. Without it, page styles can affect the element’s children, and styles inserted by the element can affect the page. A shadow root provides a style and markup boundary, but requires deliberate styling interfaces. Interactive elements also need explicit focus and keyboard behavior. section 7.8.2 section 9.4

Registration can happen after markup is parsed; :not(:defined) can provide a loading treatment until then. An unregistered tag does not throw an error, but its custom behavior will not run. The native API also leaves state updates, attribute reflection, and event dispatch to the developer. Use a helper such as Lit when that repeated work outweighs the benefit of a small plain element. section 7.6.3 section 14.3

How Vanilla Web covers it

How deep it goes
Works through class creation, registration, connection, independent instances, and public interfaces; treats customized built-ins as a later topic.
Examples
Uses a greeting tag, independent counter buttons, an e-commerce component family, and a React component wrapper.
What it assumes
Assumes JavaScript classes and DOM familiarity while introducing custom-element creation and registration step by step.
What you can do after
Build it from scratch with HTMLElement and customElements.define(), then configure it through attributes or properties and handle its events.
How it connects
Connects Custom Elements to Shadow DOM, HTML templates, attributes, properties, DOM events, CSS custom properties, and accessibility.

Also explained in

Compare how 4 books explain Custom Elements →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.