What are Web Components?
Web Components let you create CUSTOM HTML tags with their own styles and behavior, like <user-card> or <star-rating>.
What is Shadow DOM? (Isolated styles)
Shadow DOM is like a "secret room" where your component's styles won't affect the rest of the page, and page styles won't affect your component.
Complete Web Component Example:
1<!-- Use your custom tag like any other HTML tag -->
2<user-card name="Deepak Verma" role="Developer"></user-card>
3<user-card name="Jane Smith" role="Designer"></user-card>
4
5<!-- Template: defines the structure (hidden until used) -->
6<template id="cardTemplate">
7 <style>
8 /* This style stays INSIDE the component only */
9 /* It will NOT affect other elements on the page */
10 .card {
11 border: 1px solid #ccc;
12 padding: 15px;
13 margin: 10px;
14 border-radius: 8px;
15 background: #f9f9f9;
16 font-family: Arial;
17 }
18 h3 {
19 margin: 0 0 5px 0;
20 color: #333;
21 }
22 p {
23 margin: 0;
24 color: #666;
25 }
26 </style>
27 <div class="card">
28 <h3></h3> <!-- Will be filled with name -->
29 <p class="role"></p> <!-- Will be filled with role -->
30 </div>
31</template>
32
33<script>
34 // Define your custom component
35 class UserCard extends HTMLElement {
36 constructor() {
37 super();
38 // Get the template
39 const template = document.getElementById('cardTemplate');
40 // Create shadow DOM (isolation)
41 const shadow = this.attachShadow({ mode: 'open' });
42 // Copy template into shadow DOM
43 shadow.appendChild(template.content.cloneNode(true));
44 }
45
46 // This runs when component is added to page
47 connectedCallback() {
48 // Read attributes from the tag
49 const name = this.getAttribute('name');
50 const role = this.getAttribute('role');
51
52 // Fill the template with actual data
53 this.shadowRoot.querySelector('h3').textContent = name;
54 this.shadowRoot.querySelector('.role').textContent = role;
55 }
56 }
57
58 // Register your custom tag
59 customElements.define('user-card', UserCard);
60</script>Why Use Web Components?
Benefit | Explanation |
|---|---|
Reusability | Write once, use anywhere (multiple pages, multiple projects) |
Encapsulation | Styles don't leak in/out (no CSS conflicts) |
Framework independent | Works with React, Vue, Angular, or plain HTML |
Native | No extra libraries needed (pure browser API) |
