Module 15: Modern Interactive HTML
Custom Elements, Shadow DOM, and Slots
Understand the building blocks of Web Components and how a component can encapsulate its internal markup.
Web Components are browser platform features for creating reusable custom elements. Three important pieces are custom elements, Shadow DOM, and templates/slots.
A custom element name must contain a hyphen:
<user-badge name="Asha"></user-badge>
JavaScript can define the element by extending HTMLElement and registering it with customElements.define(). Shadow DOM lets a component keep an internal DOM tree separate from the page’s ordinary tree. A slot marks where the component can display content supplied by the page.
<template id="badge-template">
<style>span { border-radius: 999px; padding: .25rem .6rem; }</style>
<span><slot></slot></span>
</template>
The example shows a template with a slot, but a complete custom element also needs JavaScript to clone the template and attach a shadow root.
Web Components can be useful for reusable widgets shared across applications or technology stacks. They also introduce lifecycle, styling, and accessibility decisions. A component that renders a custom control must still expose an understandable name, keyboard behavior, and state. Do not build a custom element for something native HTML already does well.