HTML Web Components

Introduction

Web Components let you create reusable custom HTML elements with their own logic, styles, and encapsulation. They work in all modern browsers without frameworks. Perfect for UI widgets, dashboards, reusable components, and dynamic content.

1. Creating a Custom Element

class HelloBox extends HTMLElement {
  connectedCallback() {
    this.innerHTML = "

Hello from Web Component!

"; } } customElements.define("hello-box", HelloBox);

Usage:


    

2. Adding a Shadow DOM

Shadow DOM isolates your styles so they don’t leak into the page.

class MyCard extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.innerHTML = `
      

      
`; } } customElements.define("my-card", MyCard);

3. Passing Attributes

class UserTag extends HTMLElement {
  connectedCallback() {
    const name = this.getAttribute("name") || "Guest";
    this.innerHTML = `Hello, ${name}`;
  }
}

customElements.define("user-tag", UserTag);
    

Usage:


    

4. Observing Attribute Changes

class CounterBox extends HTMLElement {

  static get observedAttributes() { return ["value"]; }

  attributeChangedCallback(name, oldVal, newVal) {
    this.render();
  }

  connectedCallback() {
    this.render();
  }

  render() {
    this.innerHTML = `Count: ${this.getAttribute("value")}`;
  }
}

customElements.define("counter-box", CounterBox);
    

5. Component with Methods

class ToggleSwitch extends HTMLElement {
  constructor() {
    super();
    this.on = false;
  }

  toggle() {
    this.on = !this.on;
    this.render();
  }

  connectedCallback() {
    this.render();
    this.onclick = () => this.toggle();
  }

  render() {
    this.innerHTML = this.on ? "ON" : "OFF";
  }
}

customElements.define("toggle-switch", ToggleSwitch);
    

6. Slot Content (Like React Children)

class Box extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.innerHTML = `
      

      
`; } } customElements.define("box-wrapper", Box);

Usage


  

Inside the box

7. Styling Web Components

this.shadowRoot.innerHTML = `
  

  
`;
    

8. Component Templates

const tmpl = document.createElement("template");
tmpl.innerHTML = `
  

  

Hello

`; class HelloTemp extends HTMLElement { constructor() { super(); this.attachShadow({ mode:"open" }); this.shadowRoot.appendChild(tmpl.content.cloneNode(true)); } } customElements.define("hello-temp", HelloTemp);

9. Real Use Cases

10. Summary