DOM Manipulation in JavaScript
Introduction
DOM manipulation means creating, reading, updating, and removing page elements with JavaScript. You will query nodes, change text and attributes, build lists from data, and manage classes—core skills for any interactive website.
Prerequisites
Querying Elements
// Common selectors
const title = document.getElementById("title");
const firstBtn = document.querySelector("button.primary");
const allItems = document.querySelectorAll(".item");
console.log(title?.textContent);
console.log(allItems.length);querySelector returns first match; querySelectorAll returns a static NodeList.
Reading and Updating Text
// textContent vs innerHTML
const note = document.querySelector("#note");
if (note) {
note.textContent = "Plain text safe from HTML injection";
}Use textContent for user-facing strings; innerHTML only with trusted or sanitized HTML.
Creating and Inserting Nodes
// Build a list from data
const ul = document.createElement("ul");
const fruits = ["apple", "banana", "orange"];
for (const name of fruits) {
const li = document.createElement("li");
li.textContent = name;
ul.appendChild(li);
}
document.body.appendChild(ul);Modern alternative: element.append() accepts strings and nodes.
Attributes and Data Attributes
const link = document.createElement("a");
link.href = "https://example.com";
link.target = "_blank";
link.dataset.track = "cta-hero";
console.log(link.getAttribute("href"));
console.log(link.dataset.track);data-* attributes map to element.dataset in camelCase.
Class List API
const card = document.querySelector(".card");
if (card) {
card.classList.add("active");
card.classList.remove("hidden");
card.classList.toggle("selected");
console.log(card.classList.contains("active"));
}Prefer classList over className string juggling.
Removing Nodes
const stale = document.querySelector(".stale");
stale?.remove();Mini Example: Render Todo List
<div id="app"></div>
<script>
const todos = [
{ id: 1, text: "Learn DOM", done: false },
{ id: 2, text: "Build UI", done: true },
];
const app = document.getElementById("app");
const list = document.createElement("ul");
for (const todo of todos) {
const li = document.createElement("li");
li.textContent = todo.done ? `✓ ${todo.text}` : todo.text;
if (todo.done) li.classList.add("done");
list.appendChild(li);
}
app.appendChild(list);
</script>FAQ
innerHTML performance?
Fast for bulk HTML strings; risk XSS if strings include user input.
Live vs static NodeLists?
querySelectorAll is static; some older APIs returned live lists that updated with DOM changes.
Frameworks vs DOM APIs?
React/Vue generate DOM updates for you—but still compile down to these ideas.