Templates and Slots
Compose components with template and slot.
Templates and Slots is a free JavaScript Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The template Element
The <template> element holds inert HTML that is parsed but not rendered. Its content stays out of the page until you clone and insert it, making it perfect for reusable markup.
Accessing Template Content
A template's children live in its .content property, a DocumentFragment. Scripts, images, and styles inside it are not executed or loaded until inserted.
// <template id="card"><p>Hi</p></template>
const tpl = document.getElementById('card');
const fragment = tpl.content; // DocumentFragmentCloning a Template
Use importNode or cloneNode(true) to copy the template content, then insert the clone. Cloning lets you stamp out many copies cheaply.
const tpl = document.getElementById('card');
const clone = tpl.content.cloneNode(true);
document.body.appendChild(clone);Templates Inside Components
Custom elements often define a template once and clone it into their shadow root on each instance. This is faster than re-parsing an HTML string every time.
const tpl = document.createElement('template');
tpl.innerHTML = '<p>Reusable content</p>';
class MyCard extends HTMLElement {
constructor() {
super();
const root = this.attachShadow({ mode: 'open' });
root.appendChild(tpl.content.cloneNode(true));
}
}
customElements.define('my-card', MyCard);What Is a Slot?
A <slot> is a placeholder inside a shadow tree where the element's own child content (its light DOM) is projected. This lets users pass custom content into your component.
// Shadow root markup:
// <div class="box"><slot></slot></div>
// Usage:
// <my-card>This text fills the slot</my-card>Default Slot Content
Content placed between the <slot> tags acts as a fallback. It shows only when the user provides no matching content.
// <slot>No content provided</slot>
// If the user supplies children, they replace the fallback.Named Slots
Multiple slots can coexist using the name attribute. Light DOM children target a slot with the slot attribute.
// Shadow root:
// <header><slot name="title"></slot></header>
// <section><slot name="body"></slot></section>
// Usage:
// <my-card>
// <h2 slot="title">Hello</h2>
// <p slot="body">World</p>
// </my-card>The Default (Unnamed) Slot
A slot without a name is the default slot. Any child without a slot attribute is projected there. You can mix one default slot with several named slots.
// <slot name="header"></slot>
// <slot></slot> <!-- default: catches everything else -->Styling Slotted Content
Use the ::slotted() pseudo-element to style projected children from inside the shadow styles. It only matches top-level slotted nodes.
// Inside shadow <style>:
// ::slotted(p) { margin: 0; color: gray; }
// ::slotted(h2) { font-size: 1.5rem; }The slotchange Event
A slot fires a slotchange event when its assigned nodes change. Listen for it to react when users add or remove projected content.
const slot = this.shadowRoot.querySelector('slot');
slot.addEventListener('slotchange', () => {
const nodes = slot.assignedNodes();
console.log('slot now has', nodes.length, 'nodes');
});Templates and Slots Together
Templates define the structure once; slots make that structure flexible by letting consumers inject their own content. Together they power clean, reusable, customizable Web Components.
Quick Check
Test your understanding of templates and slots.
Recap
You learned templates and slots:
<template>holds inert, reusable markup in.content.- Clone with
cloneNode(true)before inserting. <slot>projects light DOM into the shadow tree.- Named slots use
nameplus the child'sslotattribute. ::slotted()styles projected nodes;slotchangereacts to updates.
You have completed Web Components. Next, the Intersection Observer API.
Frequently asked questions
Is the “Templates and Slots” lesson free?
Yes — the full text of “Templates and Slots” is free to read here on the web, and the JavaScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the JavaScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Templates and Slots”?
Compose components with template and slot. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start JavaScript Academy?
No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Templates and Slots” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this JavaScript Academy lesson?
Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Defining Custom Elements
- Lifecycle Callbacks
- Shadow DOM and Encapsulation
- Templates and Slots