liveBook · Manning

customElements.define

As explained in Web Component Development with Modern Libraries and Tooling

A browser API method that registers a custom element name with its JavaScript class.

customElements.define registers a custom element name with a JavaScript class that extends HTMLElement. After registration, matching HTML elements are upgraded into functioning web components. section 1.3 section 1.4

Registering a hello-world component

class HelloWorld extends HTMLElement {\n connectedCallback() {\n this.innerHTML = "<p>Hello, World!</p>";\n }\n}\n\ncustomElements.define("hello-world", HelloWorld);\n\nUse the registered component as <hello-world></hello-world> in HTML. The class can also render attributes, styles, event behavior, and shadow content. section 3.1.1 section 1.3

Use the registration process correctly:

  • Define a class extending HTMLElement, then register it with a unique name. section 1.4 section 3.1.1
  • Choose a lowercase name containing at least one hyphen; uppercase letters and reserved SVG or MathML names are invalid. section 3.1.1
  • Avoid registering the same name twice; check customElements.get before defining it when duplicate loading is possible. section 3.1.1
  • Load the JavaScript into the page and include matching custom elements in the HTML. section 1.4
class HelloWorld extends HTMLElement {
  connectedCallback() { #1
    this.innerHTML = "<p>Hello, World!</p>"; #2
  }
}

customElements.define("hello-world", HelloWorld); #3

Shows the smallest complete registration: an HTMLElement subclass, connectedCallback rendering, and the customElements.define call. section 3.1.1

How Web Component Development with Modern Libraries and Tooling covers it

How deep it goes
Defines registration, naming constraints, duplicate errors, subclass requirements, and upgrade behavior without descending into implementation internals.
Examples
Uses hello-world elements, a name attribute, greeting markup, scoped styling, and a guarded duplicate-registration pattern.
What it assumes
Assumes basic JavaScript classes and HTML, while teaching the registration workflow and custom element naming rules.
What you can do after
Builds a vanilla web component, registers it safely, loads its script, and uses its custom element in HTML.
How it connects
Connects web components with HTMLElement, customElements.get, lifecycle callbacks, HTML, CSS, JavaScript, and shadow DOM.

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 Web Component Development with Modern Libraries and Tooling. The section links point to the parts of the book it draws on.