liveBook · Manning

customElements.define

As explained in Vanilla Web

A browser method that registers a custom element name with its constructor and optional built-in-element extension options.

Use customElements.define(name, constructor, [options]) to make a JavaScript-defined element available as an HTML tag. For an autonomous element, the constructor is a class extending HTMLElement. The name must contain a hyphen and must not already be registered. section 7.6.3

Listing 7.1 Our first custom element
// hello-world.js
class HelloWorldElement extends HTMLElement {
  connectedCallback() {
    // set the text when the element is inserted into the document
    this.textContent = `Hello, ${this.getAttribute('name') || 'World'}!`;
  }
}

// register the element (must include a dash in the name)
customElements.define('hello-world', HelloWorldElement);

This complete example connects the class, its connectedCallback, the registered tag name, and an attribute-driven greeting. section 7.2

After registration, write the tag with an explicit closing tag or create it with document.createElement(). The browser creates an instance of its registered class; connectedCallback runs when that instance joins the DOM. If the tag is never registered, markup using it does not throw an error: it remains an empty HTMLElement rather than gaining the class’s behavior. Prefer attributes and properties over constructor arguments, which will be undefined for instances created from HTML. section 7.6.3

Registration is one part of the web-component toolkit, not a requirement to use Shadow DOM. The optional options.extends property registers a customized built-in element; that technique is deferred. For asynchronously loaded definitions, :not(:defined) can show a loading state or hide a custom element until registration occurs. section 7.5 section 7.7

How Vanilla Web covers it

How deep it goes
Defines the signature, naming constraints, and creation behavior; defers customized built-in elements and detailed lifecycle treatment.
Examples
Uses a greeting tag, a Bitcoin-symbol tag created through DOM APIs, and a stateful counter button.
What it assumes
Assumes basic JavaScript classes and HTML markup; introduces the registration call and its constraints.
What you can do after
Build it from scratch: register an autonomous custom element, use it in HTML or JavaScript, and handle its not-yet-defined state.
How it connects
Connects CustomElementRegistry and HTMLElement to connectedCallback, DOM creation, Shadow DOM, and the :defined CSS pseudo-class.

Also explained in

Compare how 2 books explain customElements.define →

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.