Slots allows to define placeholders in an HTML template
The technology Template, Shadow DOM and custom element are known under the term web components
Status | Description |
---|---|
Slotable | The element that should be inserted in a slot |
Sloted | The element has been inserted in a slot |
Slots are identified by their name attribute
A named slot that you will find in a template
<slot name="value"><p>None</p></slot>
This example defines:
There is three sections:
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 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>
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)
);
}
}
);
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);
<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.