Lesson 24 +10 XP

Web Components

Web Components

Web components are a way to build your own reusable widgets using HTML and JavaScript. Two HTML tags help out.

template: a saved copy

<template> holds HTML that the browser does NOT show. JavaScript can copy it and use it later, like a stencil or a cookie cutter.

<template id="greeting-card">
  <div class="card">
    <h3>Hello!</h3>
    <p>Have a great day.</p>
  </div>
</template>

The content isn't displayed until JavaScript clones it:

const tpl = document.getElementById("greeting-card");
const copy = tpl.content.cloneNode(true);
document.body.appendChild(copy);

slot: a placeholder

<slot> marks a spot inside a component where you can drop custom content. Think of it like a hole in a puzzle piece where visitors can insert their own piece.

Using slots

Inside a custom element's template, you define slots with name:

<template id="my-card">
  <div class="card">
    <slot name="title">Default title</slot>
    <slot name="body">Default body</slot>
  </div>
</template>

Then visitors fill them:

<my-card>
  <span slot="title">My custom title</span>
  <span slot="body">My custom body!</span>
</my-card>

The slot global attribute

The slot global attribute on a child element says "put me in the slot with this name."

TL;DR

  • <template> stores invisible HTML that JS can copy.
  • <slot> is a placeholder for custom content.
  • Web components let you build reusable widgets.
  • Slots connect via the name and the slot attribute.