JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 11: The Document Object ModelLesson 54 of 150About 45 minutes

Lesson 54: Creating and removing elements

01Opening question

A to-do app starts empty and grows as you add tasks. Where do those new list items come from?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

createElement makes a new element in memory; append puts it on the page.

const list = document.querySelector("#list");
const li = document.createElement("li");
li.textContent = "Walk the dog";
list.append(li);
console.log(list.children.length);

03Objective and prerequisites

Learning objective: Create elements with createElement, insert them with append, prepend, before and after, remove them, re-render lists from data, and clone templates.

You need: Lesson 53: Reading and changing content, Lesson 32: map and transformations

Skills practised: The DOM, Creating and removing elements.

04Explanation

document.createElement("li") creates a new element that is not on the page yet.

Set its content with textContent, then place it with parent.append(el) (at the end) or parent.prepend(el) (at the start).

el.before(other) and el.after(other) insert next to an existing element; el.remove() takes an element off the page.

To show a list from an array, create one element per item. parent.replaceChildren(...elements) swaps the old content for the new in one step.

05Definitions

createElement
Creates a new element node that is not yet in the page.
append / prepend
Insert nodes or text at the end or start of an element.
remove
Takes an element out of the DOM.
replaceChildren
Replaces all of an element's children with the given nodes.
template element
An HTML element whose content is inert until cloned with JavaScript.

Open the full glossary

06Visual learning object

Element creation laboratory. Create, insert, move and remove elements in a live preview and watch the list change.

Loading the interactive object…

Open the full Element creation laboratory page with its guided experiment.

07Examples

ex-054-01Create and append Browser page (sandboxed preview)

A new element appears only after it is inserted.

const list = document.querySelector("#list");
const li = document.createElement("li");
li.textContent = "Book dentist";
console.log(list.children.length);
list.append(li);
console.log(list.children.length, list.lastElementChild.textContent);
Sample input
None
Expected output
2 3 Book dentist

The list shows three items, ending with Book dentist.

Common mistake
Creating the element and forgetting to append it.
Try this
Use prepend instead and check firstElementChild.
Source
examples/ex-054-01-append.js

ex-054-02Render a list from data Browser page (sandboxed preview)

One element per array item, inserted in one step.

const products = ["Tea", "Cake", "Juice"];
const list = document.querySelector("#products");
const items = products.map((name) => {
  const li = document.createElement("li");
  li.textContent = name;
  return li;
});
list.replaceChildren(...items);
console.log([...list.children].map((li) => li.textContent).join(", "));
Sample input
None
Expected output
Tea, Cake, Juice
Common mistake
Building an HTML string with user data and assigning innerHTML.
Try this
Add a price to each product and show it in the text.
Source
examples/ex-054-02-render-array.js

ex-054-03Remove elements Browser page (sandboxed preview)

remove() takes an element off the page.

document.querySelectorAll("#tasks .done").forEach((li) => li.remove());
const left = document.querySelectorAll("#tasks li");
console.log(left.length, left[0].textContent);
Sample input
None
Expected output
1 Write report
Common mistake
Removing items while looping over a live children collection and skipping some.
Try this
Remove the remaining task too and check the length.
Source
examples/ex-054-03-remove.js

ex-054-04Insert in the right place Browser page (sandboxed preview)

before, after and prepend control the position.

const mix = document.querySelector("#b");
const make = (text) => Object.assign(document.createElement("li"), { textContent: text });
mix.before(make("Measure"));
mix.after(make("Bake"));
document.querySelector("#steps").prepend(make("Preheat"));
console.log([...document.querySelectorAll("#steps li")].map((li) => li.textContent).join(" > "));
Sample input
None
Expected output
Preheat > Measure > Mix > Bake
Common mistake
Appending everything and then trying to sort the elements.
Try this
Move Bake to the start by prepending the existing element.
Source
examples/ex-054-04-positions.js

ex-054-05Clone a template Browser page (sandboxed preview)

A template keeps markup in HTML; JavaScript clones and fills it.

const tpl = document.querySelector("#card-tpl");
const cards = document.querySelector("#cards");
for (const p of [{ name: "Mug", price: 8 }, { name: "Lamp", price: 30 }]) {
  const card = tpl.content.cloneNode(true);
  card.querySelector("h3").textContent = p.name;
  card.querySelector(".price").textContent = `$${p.price}`;
  cards.append(card);
}
console.log(cards.children.length, cards.querySelector("h3").textContent);
Sample input
None
Expected output
2 Mug
Common mistake
Appending tpl itself instead of a clone of tpl.content.
Try this
Add a third product.
Source
examples/ex-054-05-template.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Add the missing item

Insert a created element into the page.

const list = document.querySelector("#list");
const li = document.createElement("li");
li.textContent = "Eggs";
console.log(list.children.length);

Render the team

Create one element per array item.

const names = ["Ada", "Grace", "Linus"];
const team = document.querySelector("#team");
// TODO: add one li per name with createElement and textContent

Re-render the to-do list

Render from data so repeated renders never duplicate items.

// Write renderTodos(list, todos)

09Prediction

Commit to an answer first, then run the real code to compare.

// HTML: <div id="a"><p id="p">x</p></div><div id="b"></div>
const p = document.querySelector("#p");
document.querySelector("#b").append(p);
console.log(document.querySelector("#a").children.length, document.querySelector("#b").children.length);

What is printed?

10Debugging investigation

Tasks appear twice after adding one

After adding "Call Sam", the list shows five items: the first two tasks appear twice.

const tasks = ["Pay rent", "Buy milk"];
const list = document.querySelector("#tasks");
function render() {
  for (const t of tasks) {
    const li = document.createElement("li");
    li.textContent = t;
    list.append(li);
  }
}
render();
tasks.push("Call Sam");
render();
console.log("Items shown: " + list.children.length);

More cases in the Debugging Detective Laboratory

11Practical scenario

Rendering from data

A notes app keeps its notes in an array. Whenever a note is added or deleted, a render function rebuilds the list from the array with replaceChildren, so the page always matches the data.

// function render() {
//   list.replaceChildren(...notes.map(noteElement));
// }
console.log("Data changes, then render() rebuilds the list");

12Knowledge check

1. Where is an element right after document.createElement("li")?

  • At the end of the body
  • Nowhere on the page yet
  • Inside the first ul
  • In the head

2. With <ul id="u"><li>A</li></ul>, what is printed?

const li = document.createElement("li");
li.textContent = "B";
document.querySelector("#u").prepend(li);
console.log(document.querySelector("#u").firstElementChild.textContent);
  • A
  • B
  • AB
  • An error

3. Why does the list grow by three items every time render() runs?

function render() {
  for (const n of ["A", "B", "C"]) list.append(Object.assign(document.createElement("li"), { textContent: n }));
}
  • It appends without clearing the old items
  • map returns too many items
  • createElement duplicates
  • append copies elements

4. What does el.remove() do?

  • Deletes the variable
  • Takes the element out of the DOM
  • Clears its text only
  • Hides it with CSS

5. Why clone tpl.content instead of appending it?

  • Templates cannot be cloned
  • So the template can be reused for every item
  • To make it faster only
  • content is read-only text

6. Showing a list of user comments: which is safer?

  • list.innerHTML += <li>${c}</li> for each comment
  • Create li elements and set textContent
  • document.write each comment
  • Use eval to build HTML

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Add the missing item: Prints 3; Eggs is last
  • Render the team: Three items in order; No innerHTML
  • Re-render the to-do list: Prints 2; Done item text and class; Empty list clears

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-11-the-document-object-model/lesson-054-creating-and-removing-elements/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • createElement makes an element; append, prepend, before and after insert it.
  • remove() takes an element out of the page.
  • Render lists from data with replaceChildren to avoid duplicates.
  • Templates keep reusable markup in HTML.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation creating and removing DOM elements
Context: I am learning creating and removing DOM elements in JavaScript.
Task: Explain createElement, append, remove and replaceChildren with a to-do list.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction creating and removing DOM elements drill
Context: I have practised creating and removing DOM elements.
Task: Give me six snippets that insert, move and remove elements and ask what the page shows.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging creating and removing DOM elements bug
Context: My list shows every item twice after I add a new one.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation creating and removing DOM elements practice
Context: I finished the creating and removing DOM elements exercises.
Task: Create three exercises that render lists from arrays.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review creating and removing DOM elements review
Context: Here is my code that uses creating and removing DOM elements.
Task: Review my rendering code for duplicates, innerHTML with user data and unnecessary DOM writes.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.