<template> & cloneNode
Reuse markup with templates
Lesson 4 of 20 · 10 min · Module 1: The page is a tree
Creating every element by hand gets long when each item has several parts. A template keeps the markup in HTML, where it is easy to read and style, and JavaScript only fills in the blanks.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Keep repeated markup in a <template>
- Clone and fill template content
- Combine templates with data
The idea
Content inside <template> is not shown on the page. Its content property holds a ready-made piece of DOM. template.content.firstElementChild.cloneNode(true) makes a deep copy you can fill with querySelector and textContent, then append.
const template = document.querySelector('#row-template');
const row = template.content.firstElementChild.cloneNode(true);
row.querySelector('.name').textContent = 'Ana';
document.querySelector('#rows').append(row);
01Inert until used
The browser parses a template but does not show it, load its images or run its scripts. It is a blueprint waiting to be copied.
02Clone, never move
Appending template.content directly moves its nodes out of the template, so the second item finds it empty. cloneNode(true) copies the element and all of its children, leaving the template intact.
const copy = template.content.firstElementChild.cloneNode(true); // deep copy
const shallow = element.cloneNode(); // only the element, no children
03Markup stays in HTML
Designers can change the card’s structure in the template without touching JavaScript, as long as the class names the script looks for stay the same.
Your turn
#card-template, fill .card-title with the title and .card-level with the level, add the class is-new when isNew is true, and append the card to #cards. The template itself must stay unchanged so it can be reused.What the checks look for
- Three cards are created from the template
- Titles and levels are filled in
- Only new topics are marked
- The template stays empty and reusable
- It works with other data
Take this with you
Templates keep markup in HTML; JavaScript only fills it in.
Go a little further
Add a <span class="badge">New</span> to the template and remove it from cards that are not new.