Once an element exists, you can place it where you want, move it, or delete it.
Adding
| Method | Puts the new node… |
|---|---|
parent.append(node) | as the last child |
parent.prepend(node) | as the first child |
element.before(node) | right before the element |
element.after(node) | right after the element |
element.replaceWith(node) | instead of the element |
<ul id="list"><li id="b">B</li></ul>
<script>
const list = document.querySelector("#list");
const make = text => Object.assign(document.createElement("li"), { textContent: text });
list.append(make("C"));
list.prepend(make("A"));
document.querySelector("#b").after(make("B2"));
console.log([...list.children].map(li => li.textContent)); // → ["A", "B", "B2", "C"]
</script>
append accepts several nodes and even plain strings: p.append("Hello ", strongElement).
Removing
<ul id="list"><li>One</li><li id="two">Two</li><li>Three</li></ul>
<script>
document.querySelector("#two").remove();
console.log(document.querySelectorAll("#list li").length); // → 2
</script>
To empty a container: list.replaceChildren().
Moving
Inserting an element that is already on the page moves it, it does not copy it.
<ul id="a"><li id="item">Moving</li></ul>
<ul id="b"></ul>
<script>
document.querySelector("#b").append(document.querySelector("#item"));
console.log(document.querySelectorAll("#a li").length); // → 0
console.log(document.querySelectorAll("#b li").length); // → 1
</script>
insertAdjacentHTML
Inserts an HTML string at a position, without replacing the existing content (so it is faster than innerHTML +=). Positions are beforebegin, afterbegin, beforeend, afterend.
list.insertAdjacentHTML("beforeend", "<li>New item</li>");
Only use it with HTML you wrote, not text from users. See textContent vs innerHTML.
A tiny to-do list
<input id="task" placeholder="New task">
<button id="add">Add</button>
<ul id="tasks"></ul>
<script>
const input = document.querySelector("#task");
const tasks = document.querySelector("#tasks");
document.querySelector("#add").addEventListener("click", () => {
const text = input.value.trim();
if (!text) return;
const li = document.createElement("li");
li.textContent = text + " ";
const del = document.createElement("button");
del.textContent = "x";
del.addEventListener("click", () => li.remove());
li.append(del);
tasks.append(li);
input.value = "";
input.focus();
});
</script>
Add a task, then remove one with its button. The full version is in the To-Do List project.
Older methods
appendChild(), insertBefore() and removeChild() still work and you will see them in older code. The newer methods above are shorter and do the same jobs.