Extending HTMLElement

To create a custom element, you need to create a JavaScript class that extends HTMLElement:

class MyCustomElement extends HTMLElement {
  constructor() {
    super();
    // Element functionality written here
  }
}

Custom Element Naming

When naming custom elements, follow these rules:

  • The name must contain a hyphen (-). This is to ensure that there are no naming conflicts with current or future standard HTML elements.
  • You can't register the same tag name more than once.
  • Custom elements can't be self-closing. They must have separate opening and closing tags.

Examples of valid custom element names:

  • <my-element>
  • <my-awesome-app>

Defining a Custom Element

To define a custom element, use the customElements.define() method:

customElements.define('my-element', MyCustomElement);

This associates the MyCustomElement class with the <my-element> tag.

Example

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

customElements.define('my-element', MyCustomElement);