Creating and Removing Elements
Most pages are built partly by JavaScript: a list of payments loaded from a server, a new row when a form is submitted, a message that appears and disappears. Creating elements with document.createElement, filling them safely, and inserting them with append and its relatives is the standard, XSS-safe way to do it. The <template> element lets you keep larger pieces of markup in the HTML and clone them, and a DocumentFragment lets you insert many elements in one step.
In One Minute
document.createElement("li")creates an element that isn't on the page yet.- Fill it with
textContent,classList,datasetandsetAttribute, then insert it. - Insert with
parent.append(...),prepend(...), or relative to an element withbefore(...),after(...). - Remove with
element.remove(); swap withelement.replaceWith(newElement); clear a container withreplaceChildren(). - For repeated markup, clone a
<template>; for many inserts, build them in aDocumentFragmentfirst.
Creating and Inserting
Syntax
const el = document.createElement("tagName");
el.textContent = "...";
parent.append(el); // last child
parent.prepend(el); // first child
sibling.before(el); // just before sibling
sibling.after(el); // just after siblingExample
<ul id="payments"><li>Navika: $120</li></ul>
<script>
const list = document.querySelector("#payments");
const li = document.createElement("li");
li.textContent = "Srihitha: $85";
li.className = "new";
list.append(li);
const first = document.createElement("li");
first.textContent = "Header";
list.prepend(first);
list.append("plain text node", document.createElement("hr"));
console.log(list.children.length);
console.log([...list.children].map((c) => c.tagName + ":" + c.textContent).join(" | "));
</script>4
LI:Header | LI:Navika: $120 | LI:Srihitha: $85 | HR:Explanation: a new element exists only in memory until you insert it. append and prepend accept several arguments, and strings among them are inserted as text nodes (safely, like textContent). The plain text isn't an element, so it isn't in children.
Insertion Methods
| Method | Inserts | Called on |
|---|---|---|
append(...nodes) | As the last children | The parent |
prepend(...nodes) | As the first children | The parent |
before(...nodes) | Just before this element | A sibling |
after(...nodes) | Just after this element | A sibling |
replaceWith(...nodes) | In place of this element | The element being replaced |
replaceChildren(...nodes) | As the only children (removes the rest) | The parent |
insertAdjacentElement(position, el) | At "beforebegin", "afterbegin", "beforeend", "afterend" | A reference element |
appendChild(node), insertBefore(node, ref) | Older single-node versions | The parent |
The older appendChild and insertBefore still work and appear in lots of code; append, prepend, before and after are shorter and accept text and several nodes at once.
Removing and Replacing
<ul id="fees">
<li id="tuition">Tuition</li>
<li id="books">Books</li>
<li id="lab">Lab</li>
</ul>
<script>
document.querySelector("#books").remove();
const bus = document.createElement("li");
bus.textContent = "Bus pass";
document.querySelector("#lab").replaceWith(bus);
const list = document.querySelector("#fees");
console.log([...list.children].map((li) => li.textContent).join(", "));
list.replaceChildren();
console.log(list.children.length);
</script>Tuition, Bus pass
0remove() takes an element off the page; you can still keep a reference and insert it again later. replaceChildren() with no arguments removes every child, which is the clean way to empty a container (list.innerHTML = "" works too).
Templates
Building a complex element with many createElement calls is verbose. A <template> element holds markup that the browser parses but doesn't display. JavaScript clones its content, fills in the parts, and inserts the clone:
<template id="payment-row">
<tr>
<td class="name"></td>
<td class="amount"></td>
<td><button type="button" class="remove">Remove</button></td>
</tr>
</template>
<table><tbody id="rows"></tbody></table>
<script>
const template = document.querySelector("#payment-row");
const rows = document.querySelector("#rows");
for (const p of [{ name: "Navika", amount: 120 }, { name: "Advitha", amount: 45 }]) {
const row = template.content.cloneNode(true);
row.querySelector(".name").textContent = p.name;
row.querySelector(".amount").textContent = `$${p.amount}`;
rows.append(row);
}
console.log(rows.children.length);
console.log(rows.querySelectorAll("button.remove").length);
console.log(rows.rows[1].cells[0].textContent);
</script>2
2
AdvithaThe markup stays in HTML where it is easy to read, and the data still goes in through textContent, so it stays safe from XSS.
Document Fragments
Every insertion into the live page can make the browser recalculate layout. When adding many elements, build them in a DocumentFragment, an invisible container, and insert the fragment once. Its children move into the page together:
<ul id="list"></ul>
<script>
const fragment = document.createDocumentFragment();
for (let grade = 9; grade <= 12; grade++) {
const li = document.createElement("li");
li.textContent = `Grade ${grade}`;
fragment.append(li);
}
console.log(fragment.children.length);
document.querySelector("#list").append(fragment);
console.log(fragment.children.length, document.querySelectorAll("#list li").length);
</script>4
0 4After insertion, the fragment is empty: its children were moved. parent.append(...arrayOfElements) and replaceChildren(...arrayOfElements) give the same single-insertion benefit without a fragment.
Rendering a List from Data
A common pattern: keep the data in an array, and re-render the whole list from it whenever the data changes. replaceChildren with mapped elements does it in one line:
<ul id="students"></ul>
<script>
const list = document.querySelector("#students");
function render(students) {
list.replaceChildren(
...students.map((s) => {
const li = document.createElement("li");
li.textContent = `${s.name} (grade ${s.grade})`;
return li;
})
);
}
let students = [{ name: "Navika", grade: 9 }, { name: "Srihitha", grade: 11 }];
render(students);
console.log(list.textContent);
students = [...students, { name: "Advitha", grade: 9 }].toSorted((a, b) => a.grade - b.grade);
render(students);
console.log([...list.children].map((li) => li.textContent).join(" | "));
</script>Navika (grade 9)Srihitha (grade 11)
Navika (grade 9) | Advitha (grade 9) | Srihitha (grade 11)This "data in, page out" approach is simple and hard to get wrong. Frameworks like React and Angular do the same thing, but update only the elements that changed.
In Practice
The Fee Tracker adds a payment row from form values, gives it a working Remove button, and keeps a running total. All inserted text uses textContent:
<input id="name" value="Navika"> <input id="amount" value="120">
<button id="add" type="button">Add</button>
<table><tbody id="rows"></tbody></table>
<p id="total">Total: $0</p>
<script>
const rows = document.querySelector("#rows");
const totalEl = document.querySelector("#total");
function updateTotal() {
const sum = [...rows.rows].reduce((s, r) => s + Number(r.dataset.amount), 0);
totalEl.textContent = `Total: $${sum}`;
console.log(totalEl.textContent);
}
document.querySelector("#add").addEventListener("click", () => {
const tr = document.createElement("tr");
tr.dataset.amount = document.querySelector("#amount").value;
const name = document.createElement("td");
name.textContent = document.querySelector("#name").value;
const remove = document.createElement("button");
remove.type = "button";
remove.className = "remove";
remove.textContent = "Remove";
remove.addEventListener("click", () => { tr.remove(); updateTotal(); });
tr.append(name, remove);
rows.append(tr);
updateTotal();
});
</script>Total: $120
Total: $240
Total: $120The checker clicked Add twice and then Remove on the first row. addEventListener makes the buttons respond to clicks; events are the subject of the next chapter.
Common Mistakes
Building HTML strings with user data. list.innerHTML += `<li>${name}</li>` is an XSS hole, and += also re-parses and recreates every existing item (losing their event listeners). Use createElement and append.
Expecting append to copy. It moves the element. Use cloneNode(true) to copy.
Cloning a template without .content. template.cloneNode(true) clones the <template> element itself. Clone template.content.
Forgetting to insert. A created element does nothing until it is appended somewhere.
Practice
Challenge: Write renderTags(container, tags) that replaces the container's content with one <span class="tag"> per tag, and call it twice to show the old tags are gone.
Show solution
<div id="tags"></div>
<script>
function renderTags(container, tags) {
container.replaceChildren(
...tags.map((t) => {
const span = document.createElement("span");
span.className = "tag";
span.textContent = t;
return span;
})
);
}
const box = document.querySelector("#tags");
renderTags(box, ["sibling", "late"]);
renderTags(box, ["paid"]);
console.log(box.children.length, box.textContent);
</script>1 paidKey Takeaways
| Task | Code |
|---|---|
| Create | document.createElement("li") |
| Add at end | parent.append(el) |
| Remove | el.remove() |
| Replace | old.replaceWith(el) |
| Empty | parent.replaceChildren() |
| From a template | template.content.cloneNode(true) |
Was this tutorial helpful?