Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 122 ยท Interactive Elements

Templates and Web Components

Reuse markup with the template element, then build your own HTML tags with custom elements, encapsulate styles with shadow DOM and fill them using slots.

As pages grow, the same pieces of markup appear again and again: product cards, user badges, rating stars, notification banners. Copying and pasting the HTML works until you need to change it in thirty places. Frameworks like React and Vue solve this with components, but the web platform has its own built-in answer: web components.

Web components are a set of standards that work together. In this lesson you'll learn four of them, one at a time:

  1. <template> holds markup that isn't rendered until you clone it.
  2. Custom elements let you define your own HTML tags, like <user-badge>, with their own behavior.
  3. Shadow DOM gives an element a private piece of DOM whose styles don't leak in or out.
  4. <slot> lets the page pass its own content into those private parts.

This lesson uses some JavaScript. If The Document Object Model is new to you, skim it first.

The template element

Content inside <template> is parsed by the browser but not rendered. It isn't displayed, its images don't load and its scripts don't run. It just waits until JavaScript makes copies of it.

The template's content is available as template.content, a document fragment (a lightweight container for DOM nodes). To use it, clone it with cloneNode(true) (the true means "copy all descendants"), fill in the copy, and insert it into the page:

Rendering a list from a template

Why not just build the string "<div class=\"city\">โ€ฆ" and assign it to innerHTML? Two reasons. First, the markup stays readable HTML instead of being buried in JavaScript strings. Second, filling the copy with textContent treats data as plain text, so a city name containing <script> can't inject code into your page.

Templates can live anywhere. <template> is allowed in <head>, in <body>, and even inside elements like <table> and <select> where most elements aren't allowed. That makes it handy for table-row templates.

Custom elements

A custom element is an HTML tag you define yourself. You write a JavaScript class that extends HTMLElement and register it with customElements.define():

JavaScript
class UserBadge extends HTMLElement {
  connectedCallback() {
    this.textContent = `๐Ÿ‘ค ${this.getAttribute("name")}`;
  }
}

customElements.define("user-badge", UserBadge);

After that, <user-badge name="Ada"></user-badge> works anywhere in the page, including elements that were already there before the script ran: the browser upgrades them as soon as the definition arrives.

The name has rules:

  • It must contain a hyphen, like user-badge or x-rating. That's how the browser knows it's custom, and it guarantees that future standard elements (which never contain hyphens) won't clash with yours.
  • It must start with a lowercase letter and have no uppercase letters.
  • Each name can be defined only once per page.
  • Custom elements are never void, so always write the closing tag: <user-badge></user-badge>, not <user-badge />.

Lifecycle callbacks

The browser calls special methods on your class at key moments:

Method When it runs
constructor() When the element is created or upgraded. Call super() first. Don't read attributes or children here; they may not exist yet.
connectedCallback() Each time the element is inserted into the document. A good place to render.
disconnectedCallback() Each time it's removed. Clean up timers and listeners here.
attributeChangedCallback(name, oldValue, newValue) When one of the attributes listed in the static observedAttributes array changes.
A custom element that reacts to attributes

The buttons only change the value attribute. The element notices the change through attributeChangedCallback and redraws itself, exactly like built-in elements react to their attributes. The role and aria-label make sure screen readers hear "3 out of 5 stars" rather than a row of symbols.

Until its definition loads, a custom element is an unknown inline element with no behavior. The CSS pseudo-class :defined lets you hide or style elements that haven't been upgraded yet: star-rating:not(:defined) { visibility: hidden; }.

Shadow DOM

The star rating above uses the element's normal children. Any CSS on the page can style them, and any script can change them. For a reusable component, you often want the opposite: internal markup and styles that the page can't break by accident.

That's what shadow DOM provides. Calling this.attachShadow({ mode: "open" }) gives your element a shadow root: a separate, hidden DOM tree that's rendered in place of the element's children.

  • Styles inside the shadow root apply only inside it. A p { color: red } rule in the component doesn't affect the page's paragraphs.
  • Page styles don't reach inside it either, except inherited properties like color and font-family, and CSS custom properties (variables), which flow in on purpose so you can theme components.
  • mode: "open" lets outside scripts reach the shadow root through element.shadowRoot. "closed" hides it, though that's not a security boundary.
  • Inside the shadow root, the :host selector targets the custom element itself.

You've already used shadow DOM without knowing: the built-in controls of <video> and <input type="range"> are implemented in a similar way.

Slots: passing content in

A component with shadow DOM still needs to show content from the page, like the name and text of a profile card. Slots solve this. A <slot> element inside the shadow root is a placeholder, and the element's ordinary children (its light DOM) are shown there:

  • An unnamed <slot> receives all children that don't ask for a specific slot.
  • A named slot, <slot name="title">, receives children that have the matching attribute slot="title".
  • Content written inside a <slot> is fallback content, shown when nothing is assigned to it.
Shadow DOM with named slots

This example brings everything together: a template holds the component's markup and styles, the custom element clones it into its shadow root, and slots place the page's content. The second card has no children, so it shows the fallback text from both slots. It also sets the --card-color custom property, which passes through the shadow boundary to theme the header.

To style slotted content from inside the component, use ::slotted(), for example ::slotted(p) { font-style: italic; }. To let the page style a specific internal element, give it a part="label" attribute and select it from outside with profile-card::part(label).

Declarative shadow DOM

You can also create a shadow root directly in HTML, with no JavaScript, by putting a <template shadowrootmode="open"> as the first child of an element:

HTML
<fancy-note>
  <template shadowrootmode="open">
    <style>
      div { border-left: 4px solid gold; padding: 0.5rem; }
    </style>
    <div><slot></slot></div>
  </template>
  Remember to save your work.
</fancy-note>

The parser turns the template into the element's shadow root as the page loads. This is useful for server-rendered components, because the styled markup is visible before any script runs. It's supported in all current major browsers, but it only works when the HTML is parsed as a page. Inserting the same string with innerHTML won't create a shadow root.

One web components feature to skip. You may read about customized built-in elements, which extend existing tags with <button is="my-button">. Safari doesn't support them and has no plans to, so prefer autonomous custom elements like the ones in this lesson.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to an <img> placed inside a <template> element?

    Template content is parsed but inert. Nothing renders or loads until you clone it and insert the copy into the document.
  2. 2. Which of these is a valid custom element name?

    Custom element names must contain a hyphen and use no uppercase letters.
  3. 3. Your component should redraw whenever its size attribute changes. What do you need?

    attributeChangedCallback runs only for attributes named in observedAttributes.
  4. 4. A child element has slot="footer". Where is it displayed?

    Children with a slot attribute go into the named slot with the matching name. Others go into the unnamed slot.
  5. 5. Which statement about styles inside a shadow root is true?

    Shadow DOM scopes styles. Rules inside it don't leak out, and page rules don't leak in (apart from inherited properties and custom properties).

Summary

  • <template> holds inert markup; clone template.content with cloneNode(true) and fill it with textContent.
  • Custom elements are defined with a class that extends HTMLElement and customElements.define(); names must contain a hyphen.
  • Lifecycle callbacks (connectedCallback, disconnectedCallback, attributeChangedCallback) let elements render and react like built-in ones.
  • attachShadow() creates a shadow root with scoped styles; :host styles the element itself, and custom properties pass through for theming.
  • <slot> and slot="name" place light DOM content into a component, with fallback content when nothing is assigned.
  • <template shadowrootmode="open"> creates shadow DOM directly in HTML.

Next lesson: SVG Basics.