Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 38 ยท Custom Elements

Custom Elements: The Basics

Learn how to build a custom element from scratch: extend HTMLElement, pick a valid tag name, register it with customElements.define, and use it like any built-in tag.

A custom element is a new HTML tag that you define yourself. It has a name with a hyphen, such as <star-rating>, and a JavaScript class that decides what the tag does. Once the class is registered, the browser treats your tag like <button> or <video>: it can be written in HTML, created with document.createElement, styled with CSS, and found with querySelector.

Lit builds on this feature, so everything in this chapter applies to every Lit component you will write. We start with plain JavaScript and no library. That way you see exactly what Lit adds later, and you can debug problems at the browser level when they come up.

The smallest custom element

You need three things: a class that extends HTMLElement, a tag name with a hyphen, and one call to customElements.define.

Hello, custom element

Two instances of the tag are in the page, and each one gets its own object of the class. The method connectedCallback runs when the element is attached to the document. Here it fills the element with text and a few inline styles. Later lessons replace inline styles with shadow DOM and static styles, but the flow is the same.

Rules for tag names

The browser needs to tell your tags apart from built-in ones, today and in the future. So the standard sets rules:

  • The name must contain a hyphen: user-card, app-header, x-tooltip.
  • It must start with a lowercase ASCII letter and contain no uppercase letters.
  • It cannot be one of a few reserved names that exist in SVG and MathML, such as font-face or annotation-xml.

A name like card or UserCard throws a SyntaxError when you try to define it. The hyphen guarantees that no future HTML element will ever collide with your name, because HTML will never add a built-in tag with a hyphen.

In a bigger codebase, add a short prefix that shows who owns the component: acme-button, acme-dialog. This avoids clashes between libraries that both want to define my-button.

How registration works

customElements is a global registry that maps tag names to classes. Three methods matter most:

JavaScript
customElements.define("hello-badge", HelloBadge); // register
customElements.get("hello-badge");                 // returns the class or undefined
customElements.whenDefined("hello-badge");         // a promise for "ready"

Registration is permanent for the page. You cannot redefine a name or unregister it, and you cannot register the same class under two names. This is why a script that loads twice throws NotSupportedError. A common guard is:

JavaScript
if (!customElements.get("hello-badge")) {
  customElements.define("hello-badge", HelloBadge);
}

Lit has a @customElement decorator that does this call for you. You will see it in the TypeScript examples in the Setup and Tooling lesson.

Creating elements in JavaScript

A registered tag works everywhere a normal element works. You can use new on the class itself, or document.createElement with the tag name.

Creating custom elements with code

All three ways produce the same kind of object. Notice that connectedCallback runs when the element enters the page, which is after setAttribute in the first two cases. That timing is useful: by the time connectedCallback runs, the attributes are already there.

The constructor rules

A custom element class may have a constructor. The browser is strict about what it may do, because the element can be created by the HTML parser before it has attributes or children. Follow these rules:

  1. Call super() first, with no arguments.
  2. Do not read attributes or children. They may not exist yet.
  3. Do not add attributes or children. Creating elements with document.createElement must not have side effects.
  4. Keep it small: set default values for fields, attach a shadow root, add private listeners on this.

Put everything else in connectedCallback. Lit follows the same rules: its constructor only sets default property values, and rendering waits until the element is connected.

flowchart LR
  A["Parser or createElement"] --> B["constructor()<br/>no attributes yet"]
  B --> C["attributes set"]
  C --> D["added to the document"]
  D --> E["connectedCallback()<br/>safe to render"]

The order of events for a new custom element.

Your element is a real element

Because the class extends HTMLElement, you inherit everything: classList, dataset, addEventListener, focus(), hidden, style, and so on. A custom element is display: inline by default, like <span>. Most components set display: block or inline-block on themselves.

You also add your own API. Methods and properties on the class become the public API of the tag. The next example gives a counter a method that other code can call.

A public method on a tag

The page talks to the component through reset(). This is the pattern for every component: attributes and properties go in, events come out, and methods trigger actions. The manual render() here is what Lit automates for you.

Defining a tag is not the same as being upgraded. If the HTML for <click-counter> appears before the script runs, the browser first treats it as an unknown element and upgrades it later. The Upgrading and Defining Elements lesson covers this.

Common mistakes

  • No hyphen in the name. customElements.define("card", ...) throws.
  • Self-closing tags. <user-card /> is not valid HTML for custom elements. Always write <user-card></user-card>.
  • Work in the constructor. Setting this.innerHTML there fails with "The result must not have children" when the element is created with createElement.
  • Forgetting to call super(). The class then throws a ReferenceError on creation.
  • Defining twice. Guard against double loading, or load your module only once.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which tag name is valid for a custom element?

    A custom element name must be lowercase and contain a hyphen. A hyphen guarantees it never collides with a future built-in tag.
  2. 2. Which class does a custom element extend?

    Autonomous custom elements extend HTMLElement, so they inherit the full element API.
  3. 3. Where should you add children and read attributes?

    The constructor can run before attributes and children exist. connectedCallback runs when the element is in the document.
  4. 4. What happens if you call customElements.define twice with the same name?

    Registrations are permanent. A duplicate name throws a NotSupportedError, so guard with customElements.get().

Summary

  • A custom element is a class that extends HTMLElement, registered with customElements.define(name, Class).
  • Names need a hyphen and lowercase letters; use a prefix to avoid clashes.
  • Registration is permanent; check with customElements.get before defining.
  • Keep the constructor tiny, and render in connectedCallback.
  • Methods and properties on the class are the public API of the tag.

Next: Custom Element Lifecycle Callbacks