In this example, we use a template with three slots:
<template id="person-template">
<div>
<h2>Personal ID Card</h2>
<slot name="person-name">NAME MISSING</slot>
<ul>
<li><slot name="person-age">AGE MISSING</slot></li>
<li><slot name="person-occupation">OCCUPATION MISSING</slot></li>
</ul>
</div>
</template>
We define the <person-details>
custom element. In this case, we add styles with JavaScript, though we could have added them in a <style>
block within the <template>
with the same effect:
customElements.define(
"person-details",
class extends HTMLElement {
constructor() {
super();
let template = document.getElementById("person-template");
let templateContent = template.content;
const shadowRoot = this.attachShadow({ mode: "open" });
let style = document.createElement("style");
style.textContent =
"div { padding: 10px; border: 1px solid gray; width: 200px; margin: 10px; }" +
"h2 { margin: 0 0 10px; }" +
"ul { margin: 0; }" +
"p { margin: 10px 0; }" +
"::slotted(*) { color: gray; font-family: sans-serif; } " +
"::slotted(span) {text-decoration: underline;} ";
shadowRoot.appendChild(style);
shadowRoot.appendChild(templateContent.cloneNode(true));
}
},
);
When filling the style
element with content, you'll see that we select all slotted elements (::slotted(*)
) and give them a different font and color. This differentiates them from the slots that haven't been filled. We styled all the slotted <span>
s (::slotted(span)
) to differentiate the <span>
s from the <p>
s.
Our markup includes three custom elements, including a custom element with an invalid slot name in a source order that differs from the <template>
:
<person-details>
<p slot="person-name">Wonder Woman</p>
<span slot="person-age">Immortal</span>
<span slot="person-occupation">Superhero</span>
</person-details>
<person-details>
<p slot="person-name">Malala Yousafzai</p>
<span slot="person-age">17</span>
<span slot="person-occupation">Activist</span>
</person-details>
<person-details>
<span slot="person-age">44</span>
<span slot="not-a-slot-name">Time traveller</span>
<p slot="person-name">Dr. Who</p>
</person-details>
Result