Web Foundations

Web Components

Custom elements, shadow DOM, HTML templates, and reusable components.

Advertisement

Web Components

Custom elements, shadow DOM, HTML templates, and reusable components.

Overview

Web components are browser-native reusable components.

Key Concepts

  • Custom Elements — Define new HTML elements
  • Shadow DOM — Encapsulated DOM and styling
  • HTML Templates — Reusable markup templates
  • Lifecycle Callbacks — Connected, disconnected, attribute changed
  • Framework Agnostic — Work in any framework

Code Examples

<my-alert type="success" message="Operation completed!"></my-alert>

<script>
class MyAlert extends HTMLElement {
  static get observedAttributes() {
    return ['type', 'message'];
  }

  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
  }

  connectedCallback() {
    this.render();
  }

  attributeChangedCallback() {
    this.render();
  }

  render() {
    const type = this.getAttribute('type') || 'info';
    const message = this.getAttribute('message') || '';

    this.shadowRoot.innerHTML = `
      <style>
        :host {
          display: block;
          padding: 16px;
          border-radius: 4px;
          margin-bottom: 8px;
        }
        :host([type="success"]) { background: #d4edda; color: #155724; }
        :host([type="error"]) { background: #f8d7da; color: #721c24; }
        :host([type="info"]) { background: #d1ecf1; color: #0c5460; }
      </style>
      <div class="alert">
        <slot></slot>
        <p>${message}</p>
        <button onclick="this.closest('my-alert').remove()">Ɨ</button>
      </div>
    `;
  }
}

customElements.define('my-alert', MyAlert);
</script>

<!-- Usage -->
<my-alert type="success" message="Saved successfully!">
  <strong>Success!</strong>
</my-alert>

<my-alert type="error" message="Something went wrong">
  <strong>Error!</strong>
</my-alert>

Practice

Create a reusable tooltip web component with shadow DOM.

Advertisement