HTML - HTML Web Components (Custom Elements and Shadow DOM)

HTML Web Components allow developers to create reusable and self-contained HTML elements. These components behave like normal HTML tags but contain their own structure, style, and functionality. Web Components help in building modular and maintainable web applications.

Web Components are mainly built using three important technologies.

1. Custom Elements

Custom Elements allow developers to define new HTML tags. Instead of using only predefined elements like <div> or <p>, developers can create their own elements such as <user-card> or <product-box>.

A custom element is created using JavaScript by extending the HTMLElement class.

Example:

class MyElement extends HTMLElement {
  connectedCallback() {
    this.innerHTML = "<h2>This is a custom element</h2>";
  }
}

customElements.define("my-element", MyElement);

Now the new tag can be used in HTML:

<my-element></my-element>

When the browser loads the page, it automatically renders the custom element.

2. Shadow DOM

Shadow DOM creates a hidden and separate DOM tree inside an element. This protects styles and structure from affecting the main webpage or being affected by external CSS.

It provides style isolation.

Example:

class ShadowExample extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({ mode: "open" });
    shadow.innerHTML = `
      <style>
        p { color: blue; }
      </style>
      <p>Shadow DOM content</p>
    `;
  }
}

customElements.define("shadow-example", ShadowExample);

The styles written inside the Shadow DOM apply only to this component.

3. HTML Templates

The <template> tag stores HTML content that is not displayed immediately. It can be reused multiple times when needed.

Example:

<template id="card">
  <p>Reusable Template</p>
</template>

JavaScript can clone this template and insert it into different parts of the page.

Advantages of Web Components

Web Components improve code reusability because a component can be used in multiple pages. They keep HTML, CSS, and JavaScript together in one place. They avoid style conflicts through encapsulation and make large projects easier to manage.

Real-World Uses

Web Components are useful for creating reusable UI elements such as navigation bars, login forms, product cards, modal windows, and dashboards. Many modern frameworks also support Web Components.

Conclusion

HTML Web Components provide a modern way to build reusable and independent user interface elements. By combining Custom Elements, Shadow DOM, and Templates, developers can create powerful components that work across different projects and frameworks.