2024-12-04

Web - Create your own HTML Custom component

Custom Elements provide a standardized approach to creating reusable components without relying on specific frameworks.


Custom Elements provide a standardized approach to creating reusable components without relying on specific frameworks.

To create your own HTML Element it's actually very simple.

  1. First we need to define a JavaScript class that extends HTMLElement:
class MyElement extends HTMLElement {
  constructor() {
    super();
    // Component initialization
  }

  connectedCallback() {
    // The component is added to the DOM
    this.innerHTML = `<h1>My custom element</h1>`;
  }
}
  1. Then register the Custom Element with the browser:
customElements.define('my-element', MyElement);

That's it, now you can use it:

<my-element></my-element>

[!NOTE] Important points to note:

  • The name of the Custom Element must contain a hyphen (-) to avoid conflicts with native HTML elements.
  • Use the constructor to initialize the element’s state and connectedCallback() to add content or event listeners.
  • You can use the Shadow DOM to encapsulate the style and structure of your component.