Command Palette

Search for a command to run...

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

append, prepend, before, after, and moving

append returns undefined. The string passed to after became a text node. Appending first again moved it to the end; it didn't make a copy.

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.

append, prepend, before, after, and moving

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

false
true
undefined
[ 'First', 'Second', 'Third' ]
<h3> #text 'Total: 3 items'
[ 'Second', 'Third', 'First' ]