Lesson 35 of 55
HTMLWeb Components – Custom Elements
12 min
Course progress64%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 35 of 55
HTML12 min
Keep these ideas in mind as you work through the lesson.
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);
<my-button label='Submit'></my-button>
static get observedAttributes() and attributeChangedCallback().connectedCallback(), disconnectedCallback(), attributeChangedCallback() allow you to run code when the element is added/removed or when attributes change.open (accessible via element.shadowRoot) or closed.extends syntax – Create a custom element that extends an existing built‑in tag (HTMLButtonElement).HTMLElement (or a built‑in element)? ✅customElements.define? ✅attachShadow)? ✅dispatchEvent) used for communication? ✅Tip: Keep the component API surface small – expose only the attributes and events that consumers need.