HTML Web Components: template, slot, and Custom Elements
Build reusable HTML Web Components using template, slot, and the Custom Elements API with Shadow DOM encapsulation for modular, framework-free UI components.
Detailed Explanation
HTML Web Components
Web Components are a set of web platform APIs that let you create reusable, encapsulated HTML elements. They work natively in browsers without any framework.
template Element
The <template> element holds HTML that is not rendered until cloned by JavaScript:
<template id="card-template">
<div class="card">
<h2></h2>
<p></p>
</div>
</template>
<script>
const template = document.getElementById('card-template');
const clone = template.content.cloneNode(true);
clone.querySelector('h2').textContent = 'Title';
clone.querySelector('p').textContent = 'Description';
document.body.appendChild(clone);
</script>
slot Element
<slot> defines insertion points in a Shadow DOM where users can inject their own content:
<!-- Component definition -->
<template id="my-card">
<style>
.card { border: 1px solid #ccc; padding: 16px; }
</style>
<div class="card">
<slot name="title">Default Title</slot>
<slot>Default content</slot>
</div>
</template>
<!-- Component usage -->
<my-card>
<h2 slot="title">Custom Title</h2>
<p>This goes into the default slot.</p>
</my-card>
Custom Elements
class MyCard extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
const template = document.getElementById('my-card');
shadow.appendChild(template.content.cloneNode(true));
}
connectedCallback() {
// Called when element is added to DOM
}
disconnectedCallback() {
// Called when element is removed from DOM
}
static get observedAttributes() {
return ['title', 'variant'];
}
attributeChangedCallback(name, oldValue, newValue) {
// React to attribute changes
}
}
customElements.define('my-card', MyCard);
Key Benefits
- Encapsulation — Shadow DOM prevents style leaking
- Reusability — Works across any framework or vanilla HTML
- Native — No build step, framework, or library required
- Composability — Slots enable flexible content projection
Use Case
Web Components are used by major companies (GitHub, YouTube, Salesforce) to build framework-agnostic UI libraries. They are ideal for design systems that need to work across React, Angular, Vue, and vanilla JavaScript projects. The template and slot elements are also used outside of Web Components for efficient DOM manipulation and content projection patterns.