πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Web Components

Web Foundations🟒 Free Lesson

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>


<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.

⭐

Premium Content

Web Components

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement