Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

customElements.define — registering a custom element

customElements.define associates an element name with a constructor in the document's registry. Learn the distinction between autonomous custom elements and customized built-in elements, plus the main registration constraints.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

customElements.define(name, constructor);
customElements.define(name, constructor, { extends: baseLocalName });

customElements.define(name, constructor, options) registers a definition in the registry exposed through window.customElements and returns undefined, not an instance or a promise. This is an HTML Living Standard API, not a feature of a particular ECMAScript edition. Autonomous custom elements are supported by modern browser engines; having Node 24 in a repository does not establish availability of this API.

An autonomous element uses a class extending HTMLElement. A simple valid name, such as cktis-greeting, starts with a lowercase ASCII letter, contains a hyphen, and contains no uppercase ASCII letters; some names are also reserved. Registration enables instance creation and upgrading matching elements already present in the document. It does not itself insert a new element into the DOM.

The { extends: "button" } variant defines a customized built-in element: its class extends HTMLButtonElement, and an instance is created with document.createElement("button", { is: name }), not document.createElement(name). Check support for this variant separately in your target browsers.

An invalid name causes SyntaxError, while reusing a name or constructor in the same registry causes NotSupportedError; both are DOMException exceptions. A non-constructor argument causes TypeError. The example sets content in connectedCallback, after attachment; do not add children or attributes in the constructor. Reload the document before running it again: removing an instance does not remove its definition.

Examples

(() => {
  class CktisGreeting extends HTMLElement {
    connectedCallback() {
      this.textContent = "Hello!";
    }
  }

  customElements.define("cktis-greeting", CktisGreeting);
  const element = document.createElement("cktis-greeting");
  document.body.append(element);
  console.log(element.textContent);
  console.log(element instanceof CktisGreeting);
  element.remove();
})();

Result

Hello!
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources