DOM Manipulation
Published by Brayan K
Learn how to interact with and modify HTML elements using JavaScript — bring your webpages to life with dynamic content, styles, and interactivity.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Change a page you actually created
The DOM is the browser’s tree of nodes. A JavaScript variable can hold a reference to one of those nodes; editing that node changes the tree. It does not rewrite the original HTML file. These examples create their own small page in the editor’s Web page mode, so no hidden element from this lesson is required.
const app = document.getElementById("app");
app.innerHTML = '<h2>Reading list</h2><ul><li>Loops</li><li>Functions</li></ul>';
const list = app.querySelector("ul");
const item = document.createElement("li");
item.textContent = "DOM";
list.append(item);
list.children[0].classList.add("read");
console.log(app.querySelector("h2").textContent);
console.log(Array.from(list.children, node => node.textContent).join(", "));
console.log(list.querySelectorAll(".read").length);
// ✅ Expected output:
// Reading list
// Loops, Functions, DOM
// 1The fixed HTML string supplies the structure. The created list item is detached until append inserts it. The final queries inspect the current tree, including that new item. All later examples also supply their own elements. A detached node supports tree operations, but it is not displayed and does not have the same layout, focus or connection state as an attached node.
A selector can find nothing—or be invalid
querySelector returns the first matching element or null. querySelectorAll returns a collection, even when it is empty. A spelling mistake and running before the required markup exists can both produce null. Check the query and when it runs before adding a null guard that silently hides a missing required element.
const card = document.createElement("section");
card.innerHTML = "<h2>Notes</h2>";
console.log(card.querySelector(".summary") === null);
console.log(card.querySelectorAll(".summary").length);
card.querySelector(".summary").textContent = "Ready";
// ✅ Expected output:
// true
// 0
// ✅ Expected error:
// TypeError: Cannot set properties of null (setting 'textContent')const card = document.createElement("section");
card.innerHTML = "<h2>Notes</h2>";
const summary = card.querySelector(".summary");
if (summary !== null) {
summary.textContent = "Ready";
} else {
console.log("This card has no summary");
}
console.log(card.querySelector("h2").textContent);
// ✅ Expected output:
// This card has no summary
// NotesSelectors use CSS syntax. An invalid selector throws instead of returning null. For an ID supplied as data, getElementById accepts the raw ID; when constructing a selector, escape the ID with CSS.escape. Do not treat arbitrary text as selector syntax.
document.querySelector("[");
// ✅ Expected error:
// SyntaxError: Failed to execute 'querySelector' on 'Document': '[' is not a valid selector.const node = document.createElement("p");
node.id = "chapter:1";
node.textContent = "Start here";
document.getElementById("app").append(node);
console.log(document.getElementById("chapter:1").textContent);
console.log(document.querySelector("#" + CSS.escape(node.id)) === node);
// ✅ Expected output:
// Start here
// trueA saved collection may keep its membership or update it
The NodeList from querySelectorAll has fixed membership: adding another match does not add it to that saved list. The elements already in it are still references to actual nodes, so their text can change. By contrast, getElementsByClassName returns a live HTMLCollection that updates when membership changes. Neither collection is an Array; Array.from makes an array when array methods are needed.
const list = document.createElement("ul");
list.innerHTML = '<li class="item">A</li><li class="item">B</li>';
const snapshot = list.querySelectorAll(".item");
const live = list.getElementsByClassName("item");
const added = document.createElement("li");
added.className = "item";
added.textContent = "C";
list.append(added);
snapshot[0].textContent = "Changed";
console.log(snapshot.length, live.length);
console.log(snapshot[0].textContent);
console.log(Array.from(live, node => node.textContent).join(", "));
// ✅ Expected output:
// 2 3
// Changed
// Changed, B, CRemoving from a live collection while increasing an index can skip nodes: the remaining elements shift into lower positions. Use a snapshot for a fixed set of removals, or deliberately keep consuming the first element.
const list = document.createElement("ul");
list.innerHTML = '<li class="item">A</li><li class="item">B</li><li class="item">C</li>';
const live = list.getElementsByClassName("item");
for (let index = 0; index < live.length; index++) {
live[index].remove();
}
console.log(list.textContent);
for (const node of Array.from(live)) node.remove();
console.log(list.children.length);
// ✅ Expected output:
// B
// 0Plain text and markup are different kinds of content
Set textContent when the value is meant to be text. Angle brackets then stay text rather than creating elements. innerHTML parses markup; the examples use fixed, author-written markup only. textContent is a suitable plain-text insertion method here, not a general security check for URLs, attributes or later uses of the same data.
const note = document.createElement("p");
note.textContent = "<strong>Read this</strong>";
console.log(note.textContent);
console.log(note.children.length);
note.innerHTML = "<strong>Read this</strong>";
console.log(note.textContent);
console.log(note.children.length);
console.log(note.firstElementChild.tagName);
// ✅ Expected output:
// <strong>Read this</strong>
// 0
// Read this
// 1
// STRONGReplacing a parent’s textContent removes its old children. A variable can still refer to a removed child, but changing that detached child no longer updates the parent. Update the intended child when you need to preserve the surrounding structure.
const card = document.createElement("section");
card.innerHTML = "<h2>Title</h2><p>Old note</p>";
const title = card.querySelector("h2");
card.textContent = "Plain replacement";
title.textContent = "Changed later";
console.log(card.textContent);
console.log(card.children.length);
console.log(title.parentNode === null);
console.log(title.textContent);
// ✅ Expected output:
// Plain replacement
// 0
// true
// Changed laterCreate a node once; inserting it again moves it
append accepts nodes or text strings; appendChild accepts one node. Inserting an existing node moves that node, so it cannot occupy two parents at once. cloneNode(true) makes a separate copy of its descendant structure. Copied IDs need attention if both copies enter one document; event listeners registered with addEventListener are not copied. Event handling belongs to Events.
const left = document.createElement("ul");
const right = document.createElement("ul");
const item = document.createElement("li");
item.textContent = "Original";
left.append(item);
right.append(item);
console.log(left.children.length, right.children.length);
console.log(right.firstElementChild === item);
const copy = item.cloneNode(true);
copy.textContent = "Copy";
left.append(copy);
console.log(left.textContent, right.textContent);
console.log(copy === item);
// ✅ Expected output:
// 0 1
// true
// Copy Original
// falseA DocumentFragment can hold several prepared nodes. Appending it transfers those children into the destination and empties the fragment. This is useful for assembling a group; it is not a promise that every fragment-based change is faster.
const list = document.createElement("ul");
const fragment = document.createDocumentFragment();
for (const name of ["A", "B"]) {
const item = document.createElement("li");
item.textContent = name;
fragment.append(item);
}
console.log(fragment.childNodes.length);
list.append(fragment);
console.log(list.children.length, fragment.childNodes.length);
console.log(list.textContent);
// ✅ Expected output:
// 2
// 2 0
// ABCount elements, and set state deliberately
children contains element nodes. childNodes also includes text and comment nodes, including whitespace between tags. Use the collection that matches the question you are asking rather than assuming every child is an element.
const list = document.createElement("ul");
list.innerHTML = "\n<li>A</li>\n<!-- note -->";
console.log(list.children.length, list.childNodes.length);
console.log(list.firstChild.nodeType, list.firstElementChild.tagName);
// ✅ Expected output:
// 1 4
// 3 LIclassList edits individual class tokens without replacing unrelated classes. The two-argument form toggle(name, condition) sets membership to a Boolean state; the one-argument form reverses whatever state happens to be there. That difference matters when rendering the same data twice. A hidden property also expresses visibility directly.
const note = document.createElement("p");
note.className = "note";
const complete = true;
for (let render = 0; render < 2; render++) {
note.classList.toggle("complete", complete);
note.hidden = !complete;
}
console.log(note.className, note.hidden);
note.dataset.count = 3;
console.log(note.dataset.count, typeof note.dataset.count);
// ✅ Expected output:
// note complete false
// 3 stringdataset values are strings. Convert and validate a numeric data attribute before arithmetic; Numbers & Math owns those numeric checks. Inline style properties use JavaScript names such as backgroundColor, while reusable appearance belongs in CSS classes. A style value read from element.style describes the inline declaration, not every rule affecting its appearance.
Guided exercise: add one task and mark it complete
Fill the three blanks with the literal hints. Keep the existing task, add the new task as plain text, and set the done class from the Boolean state. The final two lines inspect the resulting tree.
const list = document.createElement("ul");
list.innerHTML = "<li>Read the prompt</li>";
const item = document.___("li"); // 👉 replace ___ with createElement
item.___ = "Run the example"; // 👉 replace ___ with textContent
item.classList.toggle("done", true);
list.___(item); // 👉 replace ___ with append
document.getElementById("app").append(list);
console.log(Array.from(list.children, node => node.textContent).join(" | "));
console.log(list.querySelectorAll(".done").length);
// ✅ Expected output:
// Read the prompt | Run the example
// 1Independent brief: render a replaceable task list
Write renderTasks(list, tasks), where list is an existing ul and tasks is an array of records containing a string label and a Boolean done. Replace the old rows on every call; create one li per record; put the label into textContent; and set the done class from the record. Return the completed-row count. Do not change the input records.
Check a label containing angle brackets, two calls with different records, and empty input. Repeated rendering should replace the list instead of duplicating it. The brief assumes valid records; deciding how a form obtains and validates them belongs to Events.
function renderTasks(list, tasks) {
const fragment = document.createDocumentFragment();
let completed = 0;
for (const task of tasks) {
const item = document.createElement("li");
item.textContent = task.label;
item.classList.toggle("done", task.done);
if (task.done) completed++;
fragment.append(item);
}
list.replaceChildren(fragment);
return completed;
}
const list = document.createElement("ul");
document.getElementById("app").append(list);
const tasks = [
{ label: "<b>Read</b>", done: true },
{ label: "Practise", done: false }
];
const before = JSON.stringify(tasks);
console.log(renderTasks(list, tasks), list.children.length);
console.log(list.children[0].textContent);
console.log(list.querySelectorAll("b").length);
console.log(JSON.stringify(tasks) === before);
console.log(renderTasks(list, [{ label: "Review", done: false }]));
console.log(list.children.length, list.textContent);
console.log(renderTasks(list, []), list.children.length);
// ✅ Expected output:
// 1 2
// <b>Read</b>
// 0
// true
// 0
// 1 Review
// 0 0
Practice quiz
What does this complete program print? const box = document.createElement("div"); box.innerHTML = "<p>A</p><p>B</p>"; console.log(box.querySelector("p").textContent); console.log(box.querySelector(".missing"));
- A null
- A undefined
- B null
- A, B null
Answer: A null. querySelector chooses the first matching element; no match returns null.
What does this complete program print? const box = document.createElement("div"); box.innerHTML = "<p>A</p>"; const items = box.querySelectorAll("p"); box.append(document.createElement("p")); console.log(items.length, box.children.length);
- 2 2
- 1 2
- 1 1
- 2 1
Answer: 1 2. The saved NodeList retains its original membership, while children reflects the current elements.
What does this complete program print? const note = document.createElement("p"); note.textContent = "<em>Hello</em>"; console.log(note.children.length); console.log(note.textContent);
- 1 Hello
- 0 Hello
- 0 <em>Hello</em>
- 1 <em>Hello</em>
Answer: 0 <em>Hello</em>. textContent inserts text without parsing the angle brackets as markup.
What does this complete program print? const a = document.createElement("div"); const b = document.createElement("div"); const item = document.createElement("p"); a.append(item); b.append(item); console.log(a.children.length, b.children.length);
- 1 1
- 1 0
- 0 0
- 0 1
Answer: 0 1. Appending an existing node moves that same node into its new parent.
What does this complete program print? const node = document.createElement("p"); node.className = "note"; node.classList.toggle("done", true); node.classList.toggle("done", true); console.log(node.className);
- note done
- note
- done
- note done done
Answer: note done. The explicit true argument ensures membership both times instead of reversing it.
What does this complete program print? const node = document.createElement("p"); node.dataset.count = 4; console.log(node.dataset.count + 1);
- 5
- 41
- undefined
- 4 1
Answer: 41. The dataset value is the string "4", so adding 1 concatenates.
What does this complete program print? const box = document.createElement("div"); box.innerHTML = "<span>A</span>"; const span = box.firstElementChild; box.textContent = "B"; span.textContent = "C"; console.log(box.textContent, span.textContent);
- C C
- B B
- B C
- A C
Answer: B C. Replacing the parent content detaches the span; its variable still refers to the detached node.
What does this complete program print? const fragment = document.createDocumentFragment(); fragment.append(document.createElement("li")); const list = document.createElement("ul"); list.append(fragment); console.log(fragment.childNodes.length, list.children.length);
- 1 1
- 1 0
- 0 0
- 0 1
Answer: 0 1. Appending a fragment transfers its children and leaves the fragment empty.
Continue this course
- Previous: Checkpoint: Data & Logic
- Next: Events — Respond to user clicks, keypresses, and form submissions
- Quick reference: JavaScript cheat sheet › DOM
- From the blog: Understanding the DOM in JavaScript