Custom Elements: Registration, Lifecycle, ElementInternals and Accessibility
How to define HTML custom elements, use lifecycle callbacks and ElementInternals for forms, ARIA, and custom CSS states.
This page summarizes the WHATWG HTML Living Standard rules for custom elements and practical patterns from Chrome Modern Web Guidance for registration, lifecycle, forms, and accessibility. Custom elements let you register a JavaScript class against a tag name so the parser and DOM APIs construct your element with predictable behavior.
Custom elements: what they are and when to use them
Section titled “Custom elements: what they are and when to use them”Custom elements are author-defined DOM elements registered with customElements.define(). Before registration, unknown tags behave like ordinary elements; after registration, the user agent upgrades matching nodes to your class.
Custom elements provide a way for authors to build their own fully-featured DOM elements. Although authors could always use non-standard elements in their documents, with application-specific behavior added after the fact by scripting or similar, such elements have historically been non-conforming and not very functional. By defining a custom element, authors can inform the parser how to properly construct an element and how elements of that class should react to changes.
— WHATWG, 4.13 Custom elements
Reach for a custom element when you need encapsulated behavior, lifecycle hooks, or a reusable scriptable API on a tag—not when a native element plus CSS is enough. Web Components Orientation warns that re-implementing native semantics (for example a custom button without a real <button>) is a common misuse; wrapping the native control inside the shadow tree preserves platform accessibility.
customElements.define: registration, naming, and the registry
Section titled “customElements.define: registration, naming, and the registry”Tag names: kebab-case with a hyphen
Section titled “Tag names: kebab-case with a hyphen”The global registry is window.customElements, a CustomElementRegistry instance. You map a name to a constructor with define(name, constructor) for autonomous custom elements, or define(name, constructor, { extends: baseLocalName }) for customized built-in elements (limited browser support—Safari has declined customized built-ins; prefer autonomous elements with a real native control inside).
MANDATORY: the tag name must be kebab-case with at least one hyphen (e.g. my-element). This is what distinguishes custom elements from current and future built-ins.
— Chrome, Web Components Orientation
Other registry methods from the spec (4.13.4 The CustomElementRegistry interface) include get(name), whenDefined(name) (Promise), upgrade(root), and scoped registries via new CustomElementRegistry() for library isolation.
Autonomous custom element: minimal define pattern
Section titled “Autonomous custom element: minimal define pattern”A typical autonomous element extends HTMLElement, declares static observedAttributes, implements callbacks, and registers once:
customElements.define("flag-icon", FlagIcon);The parser constructs FlagIcon when it sees <flag-icon>, and you can also use document.createElement("flag-icon") or new FlagIcon() after definition—see Creating an autonomous custom element.
Custom element lifecycle: callbacks, upgrades, and :defined
Section titled “Custom element lifecycle: callbacks, upgrades, and :defined”Lifecycle reactions the platform fires
Section titled “Lifecycle reactions the platform fires”Custom element reactions are author hooks the user agent queues carefully (4.13.5 Custom element reactions):
| Trigger | Callback |
|---|---|
Upgrade after define() |
Constructor (no args) |
| Connected to a document | connectedCallback |
| Disconnected | disconnectedCallback |
Moved in tree (with moveBefore()) |
connectedMoveCallback |
| Adopted into another document | adoptedCallback |
| Attribute change (if observed) | attributeChangedCallback |
| Form-associated: owner changes | formAssociatedCallback |
| Form reset | formResetCallback |
| Disabled state | formDisabledCallback |
| Value restore (navigation/autocomplete) | formStateRestoreCallback |
Reactions are delayed until just before returning to user script, so they usually feel synchronous but may batch after complex DOM operations.
Upgrade timing and progressive enhancement
Section titled “Upgrade timing and progressive enhancement”Elements can exist in markup before your script runs. Until defined, they are inert HTMLElement instances; customElements.define() upgrades every matching connected element in the document.
Because element definition can occur at any time, a non-custom element could be created, and then later become a custom element after an appropriate definition is registered. We call this process “upgrading” the element, from a normal element into a custom element.
— WHATWG, Upgrading elements after their creation
On upgrade, attributes and children may already be present—sync state in connectedCallback, not only in the constructor. Elements created off-document stay un-upgraded until connected; use customElements.upgrade(el) if you need an instance upgraded before insertion (CustomElementRegistry.upgrade).
Hide flash of unstyled behavior with :not(:defined) guarded by a timeout so content still appears if the script fails—patterns are in Custom Elements (Chrome). Pair with customElements.whenDefined() when injecting HTML that contains undefined tags.
connectedMoveCallback when moving nodes without reset
Section titled “connectedMoveCallback when moving nodes without reset”By default, moving a connected element runs disconnectedCallback then connectedCallback, which tears down and re-initializes state. Implementing connectedMoveCallback (even empty) suppresses that pair when the element is relocated with Node.moveBefore():
To opt in to a state-preserving behavior while moving, the author can implement a “connectedMoveCallback”. The existence of this callback, even if empty, would supersede the default behavior of calling “disconnectedCallback” and “connectedCallback”.
Moving custom elements documents the same rule for moveBefore() callers.
Constructor rules: what breaks createElement and the parser
Section titled “Constructor rules: what breaks createElement and the parser”Conformance requirements are strict (4.13.2 Requirements for custom element constructors):
- Call
super()first with no prior use ofthis. - No
returnexceptreturnorreturn this. - No
document.write()ordocument.open()in the constructor. - Do not read attributes or children in the constructor (often absent on first construction).
- Do not add attributes or children in the constructor.
- Defer rendering and I/O to
connectedCallback, with guards becauseconnectedCallbackcan run multiple times.
Violations are checked during creation—including work scheduled in a microtask right after construction—and can make the element unusable from the parser or createElement.
Chrome Custom Elements adds that lifecycle hooks and observedAttributes are snapshotted at define() time—adding attributeChangedCallback or extending observedAttributes later has no effect.
ElementInternals: forms, validation, shadow access, and ARIA defaults
Section titled “ElementInternals: forms, validation, shadow access, and ARIA defaults”attachInternals() returns an ElementInternals object for features meant for the component author, not consumers (4.13.7 Element internals). It throws if internals are disabled on the definition, if called twice, or if the element is not in precustomized/custom state.
Form-associated custom elements (FACE)
Section titled “Form-associated custom elements (FACE)”Set static formAssociated = true on the class, then use internals for value and validation:
Adding a static formAssociated property, with a true value, makes an autonomous custom element a form-associated custom element. The ElementInternals interface helps you to implement functions and properties common to form control elements.
setFormValue(value) submits the control’s value (string, File, or FormData). setValidity(flags, message, anchor), checkValidity(), and reportValidity() integrate constraint validation like native controls. Implement formResetCallback, formDisabledCallback, and formStateRestoreCallback for reset, <fieldset disabled>, and bfcache restore.
Form-Associated Custom Elements recommends not using a hidden <input> when FACE is available, and in formDisabledCallback disabling internal controls rather than setting disabled on the host (which can stick after the fieldset re-enables).
Feature-detect before relying on FACE:
'attachInternals' in HTMLElement.prototype && 'setFormValue' in ElementInternals.prototypeDefault ARIA role and aria-* via internals
Section titled “Default ARIA role and aria-* via internals”For custom elements, default accessibility semantics can come from ElementInternals (role, ariaChecked, and other aria* properties), used unless the light DOM overrides with role or aria-* attributes:
For a custom element element, the default ARIA role semantics are determined as follows: […] If map[“role”] exists, then return it. Return no role.
— WHATWG, Requirements related to ARIA and platform accessibility APIs
internals.role [ = value ] — Sets or retrieves the default ARIA role for internals’s target element, which will be used unless the page author overrides it using the role attribute.
Accessible Web Components prefers setting defaults through internals rather than polluting the host with ARIA attributes, while still allowing deliberate consumer overrides. Document which semantics are “strong native semantics” consumers should not override.
Custom states and the :state() pseudo-class
Section titled “Custom states and the :state() pseudo-class”internals.states is a CustomStateSet; adding a string exposes it to CSS as :state(name) on the host and on ::part():
This is done via the :state() pseudo-class. A custom element author can use the states property of ElementInternals to add and remove such custom states, which are then exposed as arguments to the :state() pseudo-class.
— WHATWG, Exposing custom element states
Use custom states for runtime styling (busy, checked not reflected to attributes); use attributes when markup or serialization must set state (Custom states). Multi-value states map to mutually exclusive boolean state names (Custom state pseudo-class).
Accessibility with Shadow DOM: focus and cross-root references
Section titled “Accessibility with Shadow DOM: focus and cross-root references”Custom elements often use shadow roots. Accessible Web Components stresses semantic markup inside the shadow tree (<button>, <nav>) and using internals for the host role when the host is the interactive control.
Focus: tabindex in connectedCallback, delegatesFocus
Section titled “Focus: tabindex in connectedCallback, delegatesFocus”Set tabIndex on the host in connectedCallback when the host carries role and state—not in the constructor (createElement can throw). Use attachShadow({ delegatesFocus: true }) when an inner native control owns interaction and label forwarding for form-associated elements; do not combine delegatesFocus: true with host-level role/state if focus should land on the host for assistive tech.
ARIA ID references do not cross shadow boundaries
Section titled “ARIA ID references do not cross shadow boundaries”MANDATORY: an id referenced by aria-labelledby, aria-describedby, aria-controls, etc. resolves only within the referencing element’s own tree. An id-based attribute in the Light DOM cannot point at an id inside a shadow tree, and vice versa; the reference is silently ignored.
— Chrome, Accessible Web Components
Use reflected element properties such as ariaLabelledByElements for outward references, or keep relationships within one tree / use aria-label text.
Attributes, properties, and common mistakes
Section titled “Attributes, properties, and common mistakes”Keep attributes and IDL properties in sync for markup and script interoperability—coerce types on read/write (Attribute ⇄ property reflection). List only attributes that need attributeChangedCallback; guard with oldVal !== newVal to avoid reflection loops.
| Mistake | Better approach |
|---|---|
| Heavy work in constructor | Initialize in connectedCallback with idempotent setup |
Assuming one connectedCallback |
Guard one-time setup; tear down in disconnectedCallback |
| Ignoring upgrade path | Read existing attributes when connected |
Hidden <input> for form value |
static formAssociated = true + setFormValue |
role/aria-* only on host for defaults |
attachInternals().role / ariaChecked |
Synthetic data-* for internal UI state |
internals.states + :state() |
Customized built-in is="..." |
Autonomous element wrapping <button> etc. |
Server-rendered hosts with declarative shadow roots must not create a second shadow root in the constructor—reuse this.shadowRoot when hydrating (Pre-rendering custom elements).
How to check this on your site
Section titled “How to check this on your site”-
Confirm names use a hyphen and match cross-cutting registration rules; in DevTools,
customElements.get('your-tag')should return your class after the module loads. -
Load the page with the definition script delayed or disabled: undefined instances should remain readable (no permanent
visibility: hidden); after the script loads,element instanceof YourClassshould be true for nodes already in the document (upgrade timing). -
For form controls, submit a test form and verify the network payload includes your control’s
namewithout a hidden native input; runelement.checkValidity()and confirm:invalidstyling whensetValiditymarks errors (Form-Associated Custom Elements). -
Inspect the accessibility tree: default
roleand states should matchElementInternalsunless you intentionally set light-DOMaria-*; test keyboard focus paths described in Accessible Web Components. -
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact wording you are asking about so it can be corrected.