Lesson 35 of 55 · HTML
Web Components – Custom Elements
Duration: 12 min
Defining Reusable Elements
Custom Elements let you create new HTML tags with encapsulated behaviour.
class MyButton extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'closed' });
const btn = document.createElement('button');
btn.textContent = this.getAttribute('label') || 'Click';
btn.addEventListener('click', () => this.dispatchEvent(new CustomEvent('press')));
shadow.appendChild(btn);
}
}
customElements.define('my-button', MyButton);
Usage
<my-button label='Submit'></my-button>
Advanced features
- Observed attributes – React to attribute changes with
static get observedAttributes()andattributeChangedCallback(). - Lifecycle callbacks –
connectedCallback(),disconnectedCallback(),attributeChangedCallback()allow you to run code when the element is added/removed or when attributes change. - Shadow DOM – Provides encapsulated markup and styles; can be
open(accessible viaelement.shadowRoot) orclosed. extendssyntax – Create a custom element that extends an existing built‑in tag (HTMLButtonElement).
Quick checklist for custom elements
- Class extends
HTMLElement(or a built‑in element)? ✅ - Registered with
customElements.define? ✅ - Shadow DOM used for encapsulation (
attachShadow)? ✅ - Lifecycle callbacks implemented as needed? ✅
- Custom events (
dispatchEvent) used for communication? ✅
Tip: Keep the component API surface small – expose only the attributes and events that consumers need.