Pages that only change existing elements can feel limited. Real interfaces add search results, list items, messages and cards while you use them. After this lesson you will be able to create elements in JavaScript, put them exactly where you want them, and remove them again.
Three steps: create, fill, insert
Making an element takes three steps. First create it, then set its content and attributes, then insert it into the page. Until the last step, the element exists only in memory.
<ul id="list">
<li>Milk</li>
</ul>
<button id="add">Add Bread</button>
<script>
const list = document.getElementById("list");
document.getElementById("add").addEventListener("click", function () {
const li = document.createElement("li"); // 1. create
li.textContent = "Bread"; // 2. fill
list.append(li); // 3. insert
});
</script>Each click adds another "Bread". The new item is a real DOM node, so you can style it, search for it and attach events to it just like one written in HTML.
Where to insert
These methods are called on an element that is already on the page:
| Method | Puts the new node |
|---|---|
parent.append(node) |
as the last child |
parent.prepend(node) |
as the first child |
ref.before(node) |
just before ref, as a sibling |
ref.after(node) |
just after ref, as a sibling |
ref.replaceWith(node) |
in place of ref |
append and prepend accept several arguments, including plain strings, which become text nodes: p.append("Total: ", strongElement). The older appendChild does one node at a time; you will see it in older code.
Inserting an element that is already in the page does not copy it. It moves it. That is a handy way to reorder items, and a classic surprise when you expected a duplicate.
<ol id="queue">
<li>First</li>
<li>Second</li>
<li>Third</li>
</ol>
<button id="jump">Move the last to the front</button>
<script>
const queue = document.getElementById("queue");
document.getElementById("jump").addEventListener("click", function () {
queue.prepend(queue.lastElementChild);
});
</script>Each click rotates the list. Nothing was created; the same node moved.
Copying with cloneNode
To get a real copy, use cloneNode. Pass true for a deep copy that includes the children, or leave it out to copy just the element itself.
<template id="card-template">
<div class="card"><strong class="name"></strong></div>
</template>
<div id="cards"></div>
<script>
const tpl = document.getElementById("card-template");
const cards = document.getElementById("cards");
["Asha", "Ravi", "Mei"].forEach(function (name) {
const copy = tpl.content.cloneNode(true);
copy.querySelector(".name").textContent = name;
cards.append(copy);
});
</script>The <template> element holds HTML that is not displayed. Its content is a fragment you can clone as many times as needed. This pattern keeps markup in HTML and data in JavaScript, which is tidier than long strings.
Clones keep the id of the original, so if you clone an element with an id you will have duplicates. Remove or change the id on the copy.
Removing elements
If you hold the element, call remove():
item.remove();To empty a container, box.replaceChildren() removes all its children in one step. Setting box.textContent = "" also works.
When removing an item that the user clicked, you often start from the button and need the element that contains it. button.closest("li").remove() finds the nearest list item above the button and removes it.
<ul id="tasks">
<li>Write notes <button class="del">Delete</button></li>
<li>Email Ravi <button class="del">Delete</button></li>
</ul>
<script>
document.querySelectorAll(".del").forEach(function (button) {
button.addEventListener("click", function () {
button.closest("li").remove();
});
});
</script>Building from data
You will often have an array of data and need an element for each entry. Loop and append:
const fruits = ["Apple", "Pear", "Plum"];
for (const fruit of fruits) {
const li = document.createElement("li");
li.textContent = fruit;
list.append(li);
}When you add many items, you can collect them first and append once, which means the browser updates the layout once. For a small list this makes no visible difference, so choose whichever is clearer.
innerHTML: convenient, with a catch
Writing list.innerHTML += "<li>" + text + "</li>" looks shorter, and it is tempting. It has two problems. If text comes from a user, it can inject markup. And += rebuilds every existing child, which throws away event listeners attached to them. Creating elements with createElement and textContent avoids both.
If you do use innerHTML, use it only with fixed strings that you wrote yourself.
Choosing the insert position
Think about what the user expects. In a chat or a log, new items usually go at the end, so use append. In a news feed or a notification list, newest first is common, so use prepend. When you are inserting relative to an existing item, such as adding a row below the one that was clicked, after is clearer than reaching for the parent and counting positions.
Order matters when several insertions happen together. If you prepend three items in a loop, they appear in reverse order, because each new one goes to the very front. If that surprises you, either loop in the opposite direction or build the items first and insert them in one call.
It also helps to keep the building of an element in a small function that returns it, such as makeItem(text). The rest of your code then reads like a story: create the item, insert it, update a counter. Small functions are easier to test and to reuse when the same kind of element is needed in a second place.
Common mistakes
- Forgetting to insert.
createElementalone shows nothing. - Expecting a copy when appending an existing node. It moves; use
cloneNode(true). - Setting
innerHTML +=in a loop. It is slow and removes listeners from existing children. - Cloning an element with an id and ending up with two of the same id.
- Calling
remove()onnull. If the selector found nothing, you get an error; check first. - Appending to the wrong parent because a selector matched an earlier element than you meant.
Exercise
Create a page with a text input, an "Add" button and an empty list. When the button is clicked, create a list item with the input text (use textContent), append it, and clear the input. Give each item a "Remove" button that deletes just that item. Ignore blank entries. Try typing <b>hi</b> and confirm it shows as plain text.
Next: Events.
Key points
- document.createElement makes an element that is not on the page until you insert it.
- append, prepend, before, after and replaceWith place elements; remove() deletes one.
- Appending an element that is already on the page moves it instead of copying it.
- cloneNode(true) makes a deep copy that you can edit and insert.
- Building elements with textContent avoids the risks of putting user input into innerHTML.