The define() method of the CustomElementRegistry interface defines a new custom element.
This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
Syntax
customElements.define(name, constructor, options);
Parameters
- name
- Name for the new custom element.
- constructor
- Constructor for the new custom element.
- options Optional
- Object that controls how the element is defined. One option is currently supported:
extends. String specifying the name of a built-in element to extend. Used to create a customized built-in element.
Return value
Void.
Examples
Autonomous custom element
The constructors for these elements must extend HTMLElement.
class BasicElement extends HTMLElement {
connectedCallback() {
this.textContent = 'Just a basic custom element.';
}
}
customElements.define('basic-element', BasicElement);
<basic-element><basic-element>
Customized built-in element
Note: Though defined in the spec, this is not presently supported in browsers.
Besides whatever enhancements we add, the following will otherwise behave like a button:
class PlasticButton extends HTMLButtonElement {
constructor() {
super();
this.addEventListener("click", () => {
// Draw some fancy animation effects!
});
}
}
// The "extends" attribute is required for, and only usable by,
// customized built-in-elements
customElements.define("plastic-button", PlasticButton, { extends: "button" });
<!-- This *WILL* work --> <button is="plastic-button">Click Me!</button> <!-- The following autonomous custom element style will *NOT* work because of our definition in JavaScript above using "extends". The element below will thus not gain the above-defined behavior nor be any different from any other unknown HTML element. --> <plastic-button>Click me</plastic-button>
Browser compatibility
Custom Elements are defined in the following specification:
| Specification | Status | Comment |
|---|---|---|
| The HTML Standard: CustomElementRegistry.define() | LS |
| Feature | Firefox (Gecko) | Chrome | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | No support | 59.0 | No support | 47.0 | 10.1 |
| Customized built-in elements | No support | No support | No support | No support | No support |
| Feature | Firefox Mobile (Gecko) | Chrome for Android | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | No support | 56.0 | No support | 47.0 | 10.1 |
| Customized built-in elements | No support | 56.0 | No support | 47.0 | No support |