DOM Creating & Removing Nodes
Real applications constantly add and remove things: a new chat message appears, a deleted item disappears, search results replace the previous ones. This chapter shows how to create elements, insert them exactly where you want, move and copy them, and remove them again.
Creating elements
document.createElement(tag) makes a new element that isn't on the page yet. Configure it (text, classes, attributes) and then insert it:
<div id="feed"></div>
<script>
const feed = document.getElementById("feed");
const card = document.createElement("article");
card.className = "post";
const title = document.createElement("h3");
title.textContent = "Hello from createElement";
const body = document.createElement("p");
body.textContent = "This paragraph was built in JavaScript.";
card.append(title, body); // assemble the pieces
feed.append(card); // now it's visible
console.log(feed.innerHTML);
</script>Building elements this way is safe for user-provided text, because textContent never interprets HTML.
Inserting in the right place
| Method | Inserts |
|---|---|
parent.append(...nodes) |
at the end of parent (accepts strings too) |
parent.prepend(...nodes) |
at the start of parent |
el.before(...nodes) |
just before el, as a sibling |
el.after(...nodes) |
just after el, as a sibling |
el.replaceWith(...nodes) |
in place of el |
el.insertAdjacentHTML(pos, html) |
parsed HTML at "beforebegin", "afterbegin", "beforeend" or "afterend" |
parent.appendChild(node) / insertBefore(node, ref) |
older single-node versions |
<style> li.new { color: #2a7; font-weight: bold; } </style>
<ul id="list">
<li>B</li>
<li id="c">C</li>
</ul>
<script>
const list = document.getElementById("list");
const c = document.getElementById("c");
const make = (text) => {
const li = document.createElement("li");
li.textContent = text;
li.className = "new";
return li;
};
list.prepend(make("A (prepend)"));
list.append(make("E (append)"));
c.after(make("D (after C)"));
c.before(make("B½ (before C)"));
list.insertAdjacentHTML("beforeend", "<li>F (insertAdjacentHTML)</li>");
console.log([...list.children].map((li) => li.textContent).join(" | "));
</script>Removing and replacing
el.remove() deletes an element from the page. parent.replaceChildren(...) removes all children at once (optionally putting new ones in their place):
<ul id="items">
<li>Keep me</li>
<li class="temp">Remove me</li>
<li class="temp">Remove me too</li>
</ul>
<button id="clean">Remove .temp items</button>
<button id="replace">Replace first item</button>
<button id="clear">Clear list</button>
<script>
const items = document.getElementById("items");
document.getElementById("clean").addEventListener("click", () => {
items.querySelectorAll(".temp").forEach((li) => li.remove());
console.log("items left:", items.children.length);
});
document.getElementById("replace").addEventListener("click", () => {
const fresh = document.createElement("li");
fresh.textContent = "Brand-new first item";
items.firstElementChild?.replaceWith(fresh);
});
document.getElementById("clear").addEventListener("click", () => {
items.replaceChildren(); // remove everything
console.log("items left:", items.children.length);
});
</script>Moving and cloning
A node can only be in one place. Inserting an element that's already on the page moves it. To duplicate it instead, use cloneNode(true) (the true means "deep" — include all descendants):
<style> .box { display: inline-block; padding: 6px 10px; margin: 4px; background: #f0db4f; border-radius: 6px; } .zone { min-height: 40px; border: 1px dashed #999; margin: 6px 0; padding: 4px; } </style>
<div class="zone" id="left"><span class="box" id="star">★ star</span></div>
<div class="zone" id="right"></div>
<button id="move">Move ★ to the other zone</button>
<button id="clone">Clone ★</button>
<script>
const star = document.getElementById("star");
const left = document.getElementById("left");
const right = document.getElementById("right");
let copies = 0;
document.getElementById("move").addEventListener("click", () => {
(star.parentElement === left ? right : left).append(star); // moves, doesn't copy
});
document.getElementById("clone").addEventListener("click", () => {
const copy = star.cloneNode(true);
copy.removeAttribute("id"); // ids must stay unique
copy.textContent = `★ copy ${++copies}`;
star.after(copy);
});
</script>Note:
cloneNodecopies attributes and children but not event listeners added withaddEventListener. Event delegation (one listener on a parent) avoids that problem.
Building many elements efficiently
Every insertion can trigger layout work. When adding many elements, build them first and insert once — with a DocumentFragment or a single append(...array):
<table id="table" style="border-collapse:collapse">
<thead><tr><th>n</th><th>n²</th><th>n³</th></tr></thead>
<tbody></tbody>
</table>
<script>
const rows = [];
for (let n = 1; n <= 8; n++) {
const tr = document.createElement("tr");
for (const value of [n, n ** 2, n ** 3]) {
const td = document.createElement("td");
td.textContent = value;
td.style.cssText = "border:1px solid #ccc;padding:2px 10px;text-align:right";
tr.append(td);
}
rows.push(tr);
}
document.querySelector("#table tbody").append(...rows); // one insertion
console.log("rows added:", rows.length);
</script>Templates
For larger repeated structures, an HTML <template> keeps the markup in HTML. Its content isn't rendered; you clone it for each item:
<template id="user-card">
<div class="card"><h3 class="name"></h3><p class="email"></p></div>
</template>
<script>
const tpl = document.getElementById("user-card");
const card = tpl.content.cloneNode(true);
card.querySelector(".name").textContent = "Ada";
card.querySelector(".email").textContent = "ada@example.com";
document.body.append(card);
</script>Test yourself
What happens when you append an element that is already somewhere else on the page?
- A copy is inserted
- It is moved to the new position
- An error is thrown
- Nothing
Which method removes an element from the DOM?
- el.delete()
- el.remove()
- el.hide()
- document.remove(el)
Does cloneNode(true) copy event listeners added with addEventListener?
- Yes, always
- No
- Only click listeners
- Only if the listener was added with once