The browser
createElement, append and remove
Create a new element, put it on the page and take it away — piece by piece, with no HTML strings.
Why it exists
A page is almost never ready in advance: products arrive from the server, messages show up in a chat, tasks get added and removed. You could build new elements as a string and hand it to innerHTML, but then any string from someone else becomes markup, and the list gets rebuilt from scratch every time. createElement creates an element as an object: you set its properties — text, classes, attributes — and insert it exactly where it belongs. Safe and precise.
Where it's used
- Rendering lists from data: a catalog, a feed, a results table.
- Adding one element: a new chat message, a new to-do task.
- Removing an element: dismissing a notification, taking a product out of the cart.
- Redrawing "from scratch":
list.replaceChildren(...items.map(createItem)).
Syntax
const li = document.createElement("li"); // a new element, not on the page yet
list.append(li, "text") // at the end: elements and strings
list.prepend(li) // at the start
li.remove() // take it off the page
list.replaceChildren() // empty the listExamples
function addDish(list, name) {
const li = document.createElement("li");
li.className = "dish";
li.textContent = name;
list.append(li);
return li;
}function renderMenu(list, dishes) {
list.replaceChildren(
...dishes.map((dish) => {
const li = document.createElement("li");
li.textContent = `${dish.name} — $${dish.price}`;
return li;
}),
);
}
// renderMenu(menu, [{ name: "Latte", price: 4 }])
// — the list holds exactly one dish, however many times it is drawnfunction moveToDone(task) {
const done = document.querySelector("#done");
done.append(task); // the element moves out of its old list
}
function closeNotice(notice) {
notice.remove();
}append moves an existing element, remove takes it away.const rows = [
{ name: "Latte", price: 4 },
{ name: "Cheesecake", price: 3 },
];
const labels = rows.map((row) => `${row.name}: $${row.price}`);
labels; // → ["Latte: $4", "Cheesecake: $3"]
// Then each string goes into its own element:
// list.replaceChildren(...labels.map(toListItem))Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
createElement("li") returns an element object that has no parent yet: it lives only in memory, nothing is on screen. You can set it up at leisure — textContent, className, dataset — and only then insert it.
append(...items) takes any number of elements and strings; strings become text nodes (safely, like textContent). prepend inserts at the start, before/after — next to an element.
An element has exactly one place in the tree. Insert an element that's already on the page and it moves rather than being copied. For a copy there's el.cloneNode(true).
el.remove() takes the element out of the tree. The object itself lives on as long as something references it — you can insert it again.
replaceChildren(...items) removes every child and inserts the new ones in one operation; with no arguments it simply empties the element. It's the main tool of the "data → DOM" approach.
Traps
How it differs from…
textContentandinnerHTMLinnerHTML with a string also creates elements, but it turns other people's data into markup too.
createElement+ textContent keep "structure" and "text" apart — which is why they're safe.
When to pick something else
For a big piece of constant markup you write yourself (the page skeleton, an empty state), dozens of createElement calls read worse than HTML: markup right in the .html file or a <template> element fits better. And when the interface gets complex, frameworks take over creating and removing elements by hand.
Practice
Lessons where this appears
- A website for the Purrfect CaféTale · Chapter 18 · DOM: the page as a tree
- Cats looking for a homeLab · Chapter 18 · DOM: the page as a tree
- The Crooked SelectorBoss · Chapter 18 · DOM: the page as a tree
- How a real app is put togetherTale · Chapter 23 · Project: a to-do app
- Filtering to-dosLab · Chapter 23 · Project: a to-do app
- The Living PageBoss · Chapter 23 · Project: a to-do app