Custom elements

On this page 7

Custom elements are developer-defined HTML elements whose name, behavior and lifecycle are supplied by a JavaScript class and registered with the browser through the customElements.define() method. Once registered, a tag such as <user-avatar> behaves like any built-in HTML element: it can be written in markup, created with document.createElement(), styled with CSS and queried in the DOM.

Custom elements are one of the three core specifications behind Web components, alongside the Shadow DOM and the template element. They are defined in the HTML Living Standard maintained by WHATWG and are supported natively in all current major browsers, which means they work without any framework or build step.

How the browser registers and upgrades custom elements

A custom element exists in the browser through a custom element registry, a per-window table that maps tag names to constructor classes. The global registry is exposed as window.customElements, and calling customElements.define('user-avatar', UserAvatar) adds an entry that the parser and the DOM consult whenever that tag appears.

The process of turning an unknown tag into a working component is called an element upgrade. If markup containing <user-avatar> is parsed before the class is defined, the browser creates an undefined element that matches the CSS selector :not(:defined). When the definition later arrives, the browser runs the constructor on every existing instance, and the element switches to the :defined state. This allows scripts to load asynchronously without blocking rendering.

The browser enforces strict naming rules so that custom tags never collide with future standard elements. The following table summarizes the main constraints a valid name must meet.

RuleValid exampleInvalid example
Must contain a hyphenapp-headerappheader
Must start with a lowercase ASCII letterx-menu1-menu
Must not use uppercase lettersdata-gridData-Grid
Must not be a reserved namefont-pickerfont-face
Can be defined only once per registrymy-card defined oncemy-card defined twice
Naming rules for custom element tags

Attempting to define a name twice throws a NotSupportedError, which is a frequent problem when two bundles ship the same component library. Checking customElements.get(name) before defining avoids this collision.

Autonomous and customized built-in elements

The specification describes two kinds of custom elements. An autonomous custom element extends the generic HTMLElement class and starts with no built-in semantics. A customized built-in element extends a specific interface, such as HTMLButtonElement, and is used with the is attribute, for example <button is="copy-button">, so that it keeps the native behavior of the original tag.

The difference matters for accessibility and browser support. Autonomous elements must add roles, keyboard handling and focus management themselves, while customized built-ins inherit them. However, Safari has declined to implement customized built-ins, so production code usually relies on autonomous elements plus a polyfill or an internal native element.

AspectAutonomous custom elementCustomized built-in element
Base classHTMLElementA specific interface such as HTMLButtonElement
Markup syntax<copy-button><button is="copy-button">
Native semanticsNone by defaultInherited from the base tag
Browser supportAll major browsersChromium and Firefox, not Safari
Typical useNew widgets and design systemsEnhancing forms, links and buttons
Comparison of the two custom element kinds

Lifecycle callbacks and reactions

A custom element class reacts to changes through lifecycle callbacks, special methods that the browser invokes at defined moments. These callbacks are queued as custom element reactions and run synchronously before control returns to the script that caused the change, which keeps component state consistent with the DOM.

CallbackWhen it runsTypical work
constructorElement is created or upgradedInitialize state, attach a shadow root
connectedCallbackElement is inserted into a documentRender content, add listeners, fetch data
disconnectedCallbackElement is removed from a documentRemove listeners, cancel timers
attributeChangedCallbackAn observed attribute changesUpdate rendering from the new value
adoptedCallbackElement moves to another documentRebind document-specific resources
connectedMoveCallbackElement is moved with moveBefore()Preserve state during an atomic move
Lifecycle callbacks of a custom element

Attribute reactions only fire for names listed in the static observedAttributes getter. This opt-in design avoids performance costs on elements with many irrelevant attributes. A common practice is to reflect properties to attributes, so that element.disabled = true and disabled in markup produce the same state.

The constructor carries important restrictions. It must call super() first, must not read or add attributes or children, and must not assume the element is in a document. Work that depends on the DOM belongs in connectedCallback, which may run several times if the element is moved.

Custom elements within the wider HTML platform

Custom elements are the registration layer of web components, but they are often confused with the other specifications that accompany them. Each piece solves a separate problem, and a custom element can use any combination of them or none.

ConceptProblem it solvesRelation to custom elements
Shadow DOMEncapsulates markup and stylesOptional; attached in the constructor
Template elementHolds inert, reusable markupOptional source for cloned content
Data attributeStores custom data on any elementAlternative for simple configuration
Framework componentRenders UI through a library runtimeCan wrap or consume custom elements
ElementInternalsExposes form and ARIA behaviorGives custom elements native-like integration
How custom elements relate to neighboring concepts

Setting static formAssociated = true and calling attachInternals() creates a form-associated custom element. Such an element participates in HTML form submission, validation and reset, which previously required hidden input fields.

Limitations and common mistakes

Custom elements are powerful, but several design constraints surprise teams that adopt them. The most important is that the global registry is a single shared namespace, so two libraries cannot both define ui-button. Scoped custom element registries address this problem and are arriving in browsers, but older engines still require prefixes or polyfills.

  • Server-side rendering needs Declarative Shadow DOM, or the content stays invisible until JavaScript runs.
  • Self-closing syntax such as <my-tag /> is not valid; custom elements always need an end tag.
  • Complex data cannot be passed through attributes, which accept only strings; use properties instead.
  • Missing accessibility is common when an autonomous element replaces a native control without roles or focus handling.
  • Flash of undefined content appears unless :not(:defined) rules hide or reserve space for pending elements.

In simple terms

HTML comes with a fixed set of tags, such as paragraphs, buttons and images. Custom elements let developers invent new tags and teach the browser what each one should do. A team can create a <price-tag> or a <star-rating> tag once and then use it on any page like a normal tag.

It is similar to adding a new word to a shared dictionary. Once the word is defined, everyone who reads the page understands it. The key point is that the browser itself understands the new tag, so no special framework is needed to use it.

A practical example

A mid-sized online retailer runs three separate storefronts built with different frameworks, and each one had its own version of a product rating widget. The frontend team rebuilt the widget once as an autonomous custom element called <rating-stars>, with a value attribute, keyboard support and an ARIA slider role.

The element was published as a single JavaScript module of about 4 KB compressed and loaded on all three storefronts. Because the tag is understood by the browser, each framework simply rendered <rating-stars value="4"> in its templates. A CSS rule on rating-stars:not(:defined) reserved the correct height to prevent layout shift while the script loaded.

The result was one maintained component instead of three. A later accessibility fix was shipped once and reached every storefront on the next deployment, and the team removed roughly 1,200 lines of duplicated framework code.