Templates and Slots
Compose components with template and slot.
Templates and Slots is a free JavaScript Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, and your progress syncs across the web and the CoddyKit app. The JavaScript Academy course includes 4 lessons in total.
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.
Learn JavaScript with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 59
- Lessons
- 200
Frequently Asked Questions
Is the “Templates and Slots” lesson free?
Yes — any 3 lessons of the JavaScript Academy learning path, including “Templates and Slots”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The JavaScript Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.
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