Custom Elements

Custom Elements are a key part of the Web Components standard that allow developers to define their own HTML tags with custom templates, styles, and behaviors. This promotes reusability and modularity in web development.

Getting Started

HTML Custom Elements allow developers to define their own HTML tags, enabling the creation of reusable and encapsulated components for web applications.

JAVASCRIPT
    class MyCustomElement extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({ mode: 'open' });
    shadow.innerHTML = `<style>p { color: blue; }</style><p>Hello, Custom Element!</p>`;
  }
}

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

The example above demonstrates how to define a custom element named 'my-custom-element' with encapsulated styles and content.

HTML
    <my-custom-element></my-custom-element>
  

Once defined, the custom element can be used like any other HTML tag, as shown above.

Custom elements can also respond to attributes and lifecycle events. For example:

JAVASCRIPT
    class GreetingElement extends HTMLElement {
  static get observedAttributes() {
    return ['name'];
  }

  attributeChangedCallback(name, oldValue, newValue) {
    if (name === 'name') {
      this.shadowRoot.querySelector('p').textContent = `Hello, ${newValue}!`;
    }
  }

  constructor() {
    super();
    const shadow = this.attachShadow({ mode: 'open' });
    shadow.innerHTML = `<p>Hello, World!</p>`;
  }
}

customElements.define('greeting-element', GreetingElement);
  
HTML
    <greeting-element name="Alice"></greeting-element>
  

In this example, the custom element updates its content dynamically based on the 'name' attribute.

Back to Features

Links

MDN Documentation Web Components Repository