docs.rodeo

MDN Web Docs mirror

CustomElementRegistry: define() method

{{APIRef("Web Components")}} 

The define() method of the {{domxref("CustomElementRegistry")}}  interface adds a definition for a custom element to the custom element registry, mapping its name to the constructor which will be used to create it.

Syntax

define(name, constructor)
define(name, constructor, options)

Parameters

Return value

None ({{jsxref("undefined")}} ).

Exceptions

Description

The define() method adds a definition for a custom element to the custom element registry, mapping its name to the constructor which will be used to create it.

There are two types of custom element you can create:

To define an autonomous custom element, you should omit the options parameter.

To define a customized built-in element, you must pass the options parameter with its extends property set to the name of the built-in element that you are extending, and this must correspond to the interface that your custom element class definition inherits from. For example, to customize the {{htmlelement("p")}}  element, you must pass {extends: "p"} to define(), and the class definition for your element must inherit from {{domxref("HTMLParagraphElement")}} .

Valid custom element names

Custom element names must:

Examples

Defining an autonomous custom element

The following class implements a minimal autonomous custom element:

class MyAutonomousElement extends HTMLElement {
  constructor() {
    super();
  }
}

This element doesn’t do anything: a real autonomous element would implement its functionality in its constructor and in the lifecycle callbacks provided by the standard. See Implementing a custom element in our guide to working with custom elements.

However, the above class definition satisfies the requirements of the define() method, so we can define it with the following code:

customElements.define("my-autonomous-element", MyAutonomousElement);

We could then use it in an HTML page like this:

<my-autonomous-element>Element contents</my-autonomous-element>

Defining a customized built-in element

The following class implements a customized built-in element:

class MyCustomizedBuiltInElement extends HTMLParagraphElement {
  constructor() {
    super();
  }
}

This element extends the built-in {{htmlelement("p")}}  element.

In this minimal example the element doesn’t implement any customization, so it will behave just like a normal <p> element. However, it does satisfy the requirements of define(), so we can define it like this:

customElements.define(
  "my-customized-built-in-element",
  MyCustomizedBuiltInElement,
  {
    extends: "p",
  },
);

We could then use it in an HTML page like this:

<p is="my-customized-built-in-element"></p>

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN