Table of Contents

HTML Slot - A step by step on how to create a Template Placeholder

About

Slots allows to define placeholders in an HTML template

The technology Template, Shadow DOM and custom element are known under the term web components

Glossary
Status Description
Slotable The element that should be inserted in a slot
Sloted The element has been inserted in a slot

Properties

Name

Slots are identified by their name attribute

A named slot that you will find in a template

<slot name="value"><p>None</p></slot>

A step by step Example

This example defines:

There is three sections:

Template

The template is an HTML element that is not rendered by any browser.

The user defined / custom element uses this template to replace its own content.

This template defines:

<template id="template-id">
    <style>
      p {
        color: white;
        background-color: #666;
        padding: 5px;
      }
    </style>
    <h2>Template with Slot</h2>
    <p>
       <slot name="slot-id">Slot location definition (will be replaced)</slot>
    </p>
</template>

Light DOM

light DOM is a term that defines all custom element (ie not built-in HTML element from the specification).

custom element are elements that the developer instantiate programmatically via Javascript and defines the construction in the DOM. (later in this doc at the javascript section)

In this example, we add:

<our-custom-element>
  <span slot="slot-id">First span slot element definition</span>
</our-custom-element>
<our-custom-element>
    <ul slot="slot-id">
      <li>Second custom element slot</li>
      <li>Defined as list</li>
    </ul>
</our-custom-element>

Custom Element Definition

Via the customElement library, we declare that:

customElements.define('our-custom-element',
  class extends HTMLElement {
    constructor() {
      super();

      // When the tag `custom-element` is found
      // select the template, get its content
      const template = document.getElementById('template-id');
      const templateContent = template.content;

     // append as a child of the `custom-element` tag the template
      this.attachShadow({mode: 'open'}).appendChild(
        templateContent.cloneNode(true)
      );
    }
  }
);

Observability

With Javascript, you can gain extra information on the template replacement with:

const slottedSpan = document.querySelector('our-custom-element span');
console.log("Assigned/Replaced Slot Element: "+slottedSpan.assignedSlot.outerHTML);
console.log("Slot: "+slottedSpan.slot);

Result

Rendering

<slot>s do not move the user's light DOM (The HTML written by the user). When nodes are distributed into a <slot>, the <slot> renders their DOM but the nodes physically stay put.

Documentation / Reference