Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.6 — Creating, Inserting and Removing Elements
JavaScript · Example 3 of 3

Cards from a <template>

The template's card isn't in the document, so querySelectorAll(".card") found 0 at first. Each clone was filled and appended; the template itself stayed empty for the next use. <Deluxe> is shown as text because it went in through textContent.

document.createElement makes a new element that lives nowhere until you insert it with append, prepend, before, after or replaceWith; remove takes it out, inserting an existing element moves it, and <template> gives you ready-made markup to clone.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write addTask(text) that appends an <li class="task"> with the given text to #tasks and returns the new element. Add two tasks and log the list's texts.

02

Write moveToDone(li) that moves a task from #todo to the start of #done, and log both lists' lengths afterwards.

03

Using a <template> with a <tr>, render the rows [["Asha", 91], ["Ravi", 78]] into a <tbody> and log the number of rows.

Explain it without notes

01

Walk through creating a list item with text and a class and adding it as the first item of a list.

02

What happens when you append an element that is already in the document? How do you get a copy instead?

03

What is the <template> element for, and how do you use it?

04

Compare append with appendChild, and remove with removeChild.

Cards from a <template>

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

#document-fragment 0
2
Chair <Deluxe>
true