Tutorials JavaScript Manipulating the DOM
Ch 42 / 78
Chapter 42 Intermediate 9 min read JavaScript

Manipulating the DOM

Selecting an element is only the first step. DOM manipulation is where JavaScript truly brings pages to life — changing text, swapping styles, creating new elements, removing old ones, toggling classes, and updating attributes, all without a page reload. Master this chapter and you can build any dynamic UI from scratch.

What you'll learn
Changing text and HTML content safely
Modifying inline styles and CSS variables
Adding, removing, and toggling CSS classes
Creating, inserting, cloning, and removing elements
Reading and writing HTML attributes & data-* values
innerHTML vs textContent — security & performance

Three Pillars of DOM Manipulation

Every DOM manipulation task falls into one of three buckets. Understanding which category your task belongs to will help you pick the right API immediately:

Content & Attributes
Read & Write Data
Change what an element displays — its text, raw HTML markup, form values, or custom data-* attributes and standard HTML attributes.
APIs: textContent, innerHTML, value, setAttribute, dataset
Styles & Classes
Change Appearance
Apply inline CSS properties directly or toggle CSS class names. Classes are preferred — they keep behaviour separate from presentation.
APIs: style.*, classList.add/remove/toggle/contains
Elements & Structure
Build & Reshape
Create brand-new elements, insert them into the tree, move or clone existing ones, and remove elements you no longer need.
APIs: createElement, append, remove, cloneNode, replaceWith

Content Manipulation — textContent & innerHTML

The two most common ways to read or change what an element displays are textContent and innerHTML. They look similar but behave very differently — choosing the wrong one is a common source of XSS vulnerabilities:

// HTML: <p id="msg"><strong>Hello</strong> world</p>
const p = document.getElementById("msg");

// textContent — plain text only, no tags
p.textContent;    // "Hello world" (tags stripped)
p.textContent = "<b>Safe</b>"; // rendered as literal text, NOT bold

// innerHTML — parses HTML tags
p.innerHTML;     // "<strong>Hello</strong> world"
p.innerHTML = "<em>Italic text</em>"; // renders as <em>
textContent — safe, fast, strips all HTML tags innerHTML — parses HTML, use only with trusted content innerText — like textContent but respects CSS visibility Never set innerHTML from user input — XSS risk!
JavaScript — Content Manipulation
const el = document.querySelector("#output");

// ── textContent — safe for user-supplied strings ────────────
el.textContent = "Hello, World!";
const text = el.textContent; // read it back

// ── innerHTML — inject trusted HTML markup ──────────────────
el.innerHTML = `<strong>Bold</strong> and <em>italic</em>`;

// ── NEVER do this with user input (XSS risk!) ───────────────
const userInput = '<img src=x onerror="alert(1)">';
el.innerHTML = userInput; // ❌ DANGEROUS
el.textContent = userInput; // ✅ SAFE — renders as literal text

// ── Reading form values ─────────────────────────────────────
const input = document.querySelector('input[type="text"]');
const val = input.value; // read current value
input.value = "Pre-filled"; // set programmatically

// ── Template literals for dynamic content ──────────────────
const user = { name: "Alice", score: 92 };
el.innerHTML = `<p>🎉 <strong>${user.name}</strong> scored <em>${user.score}</em>/100</p>`;
Property Reads Writes XSS Safe? Use When
textContent Plain text only Escaped as text ✓ Safe Setting user-supplied strings
innerHTML Raw HTML string Parsed as HTML ⚠ Risky Injecting trusted markup
innerText Visible text only Escaped as text ✓ Safe Respecting CSS display rules
value Input field text Sets field value ✓ Safe Form inputs & textareas
Security Warning — XSS
Never insert user-provided text via innerHTML. An attacker can inject <script> tags or event-handler attributes that execute malicious JavaScript. Always use textContent for user data, or sanitize with a library like DOMPurify before using innerHTML.

Styles & Classes

You can change an element's appearance by either setting inline styles directly or by toggling CSS class names. The classList API is almost always the better choice — it keeps your CSS in stylesheets and your JS clean:

classList — preferred approach
1 classList.add("cls") — adds one or more classes
2 classList.remove("cls") — removes a class
3 classList.toggle("cls") — adds if absent, removes if present
4 classList.contains("cls") — returns true/false
5 classList.replace("old","new") — swap classes atomically
style.* — inline overrides
1 el.style.color = "red" — camelCase property names
2 el.style.backgroundColor — NOT background-color
3 el.style.cssText = "..." — set multiple at once
4 el.style.display = "" — empty string removes override
5 getComputedStyle(el) — reads final computed values
JavaScript — Styles & Classes
const btn = document.querySelector(".action-btn");

// ── classList — the clean way ─────────────────────────────────
btn.classList.add("active"); // add a class
btn.classList.remove("disabled"); // remove a class
btn.classList.toggle("open"); // flip on/off
btn.classList.toggle("dark", true); // force-add (2nd arg)
const isActive = btn.classList.contains("active"); // true/false
btn.classList.replace("btn-blue", "btn-red"); // swap
btn.classList.add("large", "rounded", "shadow"); // multiple at once

// ── style.* — inline overrides ────────────────────────────────
btn.style.color = "#fff"; // camelCase
btn.style.backgroundColor = "#f7df1e"; // NOT background-color
btn.style.padding = "12px 24px";
btn.style.cssText = "opacity:0; pointer-events:none;";
btn.style.opacity = ""; // clear inline override

// ── CSS custom properties (variables) ────────────────────────
document.documentElement.style.setProperty("--accent", "#f97316");

// ── Read computed (final) style ──────────────────────────────
const computed = getComputedStyle(btn);
console.log(computed.fontSize); // "16px" — includes stylesheet rules
Best Practice
Prefer classList over style.*. Define your states in CSS (.active, .hidden, .error) and let JavaScript just toggle class names. This keeps styling in CSS where it belongs, and makes theming and overriding much easier.

Attributes & data-* Dataset

HTML attributes like src, href, disabled, and aria-* can be read and written with the getAttribute / setAttribute API. For custom data, use data-* attributes accessed via the dataset property:

JavaScript — Attributes & Dataset
const link = document.querySelector("a.main-link");

// ── getAttribute / setAttribute ──────────────────────────────
link.getAttribute("href"); // "/about"
link.setAttribute("href", "/contact"); // change it
link.setAttribute("target", "_blank"); // add new attribute
link.removeAttribute("target"); // delete it
link.hasAttribute("disabled"); // false

// ── Boolean attributes ───────────────────────────────────────
const btn = document.querySelector("button");
btn.disabled = true; // DOM property — fastest way
btn.setAttribute("disabled", ""); // same result via setAttribute
btn.removeAttribute("disabled"); // re-enable

// ── data-* dataset ──────────────────────────────────────────
// HTML: <div data-user-id="42" data-role="admin">
const card = document.querySelector(".user-card");
card.dataset.userId; // "42" (data-user-id → userId)
card.dataset.role; // "admin"
card.dataset.role = "editor"; // update it
delete card.dataset.role; // remove data-role attribute

// ── aria- attributes for accessibility ──────────────────────
btn.setAttribute("aria-expanded", "true");
btn.setAttribute("aria-label", "Close menu");

Creating & Inserting Elements

The gold standard for adding new content is createElement + append. Unlike innerHTML +=, it doesn't re-parse the entire element and avoids security risks. Here is the full workflow — create, configure, then insert:

Create & Insert — workflow
1 createElement("tag") — creates a detached node
2 Set content & attrs — textContent, classList, etc.
3 parent.append(el) — inserts at end of parent
4 parent.prepend(el) — inserts at start of parent
5 el.before() / el.after() — insert as sibling
Remove & Replace — workflow
1 el.remove() — removes element from DOM
2 parent.removeChild(el) — older API, same result
3 el.replaceWith(newEl) — swap in place
4 el.cloneNode(true) — deep copy with children
5 el.innerHTML = "" — clear all children at once
JavaScript — Creating & Inserting Elements
// ── createElement → configure → insert ──────────────────────
const li = document.createElement("li"); // detached node
li.textContent = "New item";
li.classList.add("list-item", "highlight");
li.dataset.id = "42";
document.querySelector("ul").append(li); // insert at end

// ── append vs prepend vs before vs after ────────────────────
const list = document.querySelector("ul");
list.append(li); // at the end ↓
list.prepend(li); // at the start ↑
li.before(sibling); // just before li in parent
li.after(sibling); // just after li in parent

// ── Create multiple elements efficiently ─────────────────────
const fruits = ["🍎 Apple", "🍌 Banana", "🍒 Cherry"];
const ul = document.querySelector("#fruit-list");

fruits.forEach(name => {
const item = document.createElement("li");
item.textContent = name;
ul.append(item);
});

// ── Remove & Replace ────────────────────────────────────────
li.remove(); // remove from DOM

const newEl = document.createElement("span");
newEl.textContent = "Replaced!";
li.replaceWith(newEl); // swap li with span in-place

// ── cloneNode — deep copy an element ────────────────────────
const template = document.querySelector(".card-template");
const clone = template.cloneNode(true); // true = deep (includes children)
clone.querySelector(".card-title").textContent = "New Card";
document.querySelector("#card-grid").append(clone);

insertAdjacentHTML & insertAdjacentElement

insertAdjacentHTML is the fastest way to inject a chunk of trusted HTML at a precise position relative to an element — without re-parsing the element's existing children like innerHTML += does:

// ❌ AVOID: innerHTML += re-parses everything, kills event listeners
list.innerHTML += `<li>New Item</li>`; // existing listeners detached!

// ✅ BETTER: insertAdjacentHTML leaves existing children untouched
list.insertAdjacentHTML("beforeend", `<li>New Item</li>`);
JavaScript — insertAdjacentHTML positions
const target = document.querySelector(".container");

// ── Four insertion positions ─────────────────────────────────
target.insertAdjacentHTML("beforebegin", `<p>Before .container</p>`);
// ↑ inserted as previous sibling of .container

target.insertAdjacentHTML("afterbegin", `<p>First child inside</p>`);
// ↑ inserted as FIRST child of .container

target.insertAdjacentHTML("beforeend", `<p>Last child inside</p>`);
// ↑ inserted as LAST child of .container (most common)

target.insertAdjacentHTML("afterend", `<p>After .container</p>`);
// ↑ inserted as next sibling of .container

// ── insertAdjacentElement — for existing DOM nodes ───────────
const newDiv = document.createElement("div");
newDiv.textContent = "Dynamic div";
target.insertAdjacentElement("beforeend", newDiv);

// ── insertAdjacentText — safe plain text insertion ───────────
target.insertAdjacentText("beforeend", "Safe user text here");
Memory Aid
Think of the four positions as: beforebegin = before the tag opens, afterbegin = just inside the opening tag, beforeend = just before the closing tag, afterend = after the closing tag. beforeend is by far the most commonly used — it appends to the bottom of the element's children.

Key Method Reference

These are the core DOM manipulation methods you'll use in virtually every project. Bookmark this list:

el.textContent = "..."
Set or get raw text content — XSS-safe, strips all tags. Fastest for plain text updates.
el.innerHTML = "..."
Parse and inject HTML markup. Only use with trusted content — never with user input.
el.classList.toggle("cls")
Add the class if absent, remove it if present. Perfect for show/hide toggles and dark-mode switches.
document.createElement("tag")
Creates a new element node in memory — not yet in the DOM. Configure it first, then append it.
parent.append(el)
Inserts el as the last child of parent. Accepts multiple nodes and strings.
el.remove()
Removes the element from the DOM entirely. No need for a parent reference — unlike the older removeChild.
el.setAttribute("name", "val")
Sets any HTML attribute — including src, href, aria-*, or custom attributes.
el.dataset.myKey
Read or write data-my-key via the dataset object. Kebab-case in HTML becomes camelCase in JS.

Real-World Use Cases

These are the everyday DOM manipulation tasks you'll encounter in real JavaScript projects:

Dark Mode Toggle
Toggle a class on <html> or <body> to switch between light and dark themes instantly.
classList.toggle
Dynamic Lists
Create and append <li> items as users add entries to a to-do list, shopping cart, or tag list.
createElement + append
Image Swap
Change an <img> element's src attribute to swap photos in a gallery or carousel.
setAttribute
Toast Notifications
Create a new <div>, append it with a message and class, then remove it after a timeout.
createElement + remove
Form Validation
Add/remove .error classes on inputs and inject validation messages next to fields dynamically.
classList + textContent
Live Counter / Score
Update a score element's textContent on each event to show real-time numbers without re-rendering the whole page.
textContent
⚡
Free Resource
Download our JavaScript Cheat Sheet
DOM manipulation, events & selectors — all on one page.
Get Sheet

Try It — Live Editor

Experiment with DOM manipulation below. The demo builds a mini card list dynamically — edit the data array or the styling and run it to see your changes.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These are practical DOM manipulation patterns you'll reach for constantly in real JavaScript projects:

JavaScript — DOM Manipulation Recipes
// ── Show / Hide toggle ───────────────────────────────────────
const modal = document.querySelector("#modal");
modal.classList.toggle("hidden"); // CSS: .hidden { display: none; }

// ── Toast notification ───────────────────────────────────────
function showToast(message, type = "success") {
const toast = document.createElement("div");
toast.className = `toast toast-${type}`;
toast.textContent = message;
document.body.append(toast);
setTimeout(() => toast.remove(), 3000);
}
showToast("Saved successfully!");

// ── Render a list from data array ────────────────────────────
function renderList(items, container) {
container.innerHTML = ""; // clear first
items.forEach(item => {
const li = document.createElement("li");
li.textContent = item.name;
li.dataset.id = item.id;
container.append(li);
});
}

// ── Disable button while loading ─────────────────────────────
async function submitForm(btn) {
btn.disabled = true;
btn.textContent = "Saving…";
await saveData();
btn.disabled = false;
btn.textContent = "Save";
}

// ── DocumentFragment — batch insert without reflow ────────────
const frag = document.createDocumentFragment();
["A", "B", "C"].forEach(letter => {
const li = document.createElement("li");
li.textContent = letter;
frag.append(li);
});
list.append(frag); // single DOM update — one reflow
Quick Check
Which property should you use to safely insert user-supplied text into an element?
Quick Check
What does classList.toggle("active") do when the class is already present?
Chapter Summary
  • Use textContent to set or read plain text — it is XSS-safe because it treats everything as literal characters, never parsing HTML.
  • Use innerHTML only with trusted, controlled content — it parses HTML tags and can execute injected scripts from untrusted sources.
  • classList.add / remove / toggle / contains are the preferred way to change appearance — keep styles in CSS and behaviour in JS.
  • setAttribute / getAttribute / removeAttribute manage any HTML attribute. For custom data, use the dataset object with data-* attributes.
  • The create-configure-insert pattern (createElement → set properties → append) is the safest and most performant way to add new elements to the DOM.
  • el.remove() deletes an element without needing a parent reference. el.replaceWith(newEl) swaps it in place.
  • insertAdjacentHTML("beforeend", html) is faster than innerHTML += because it doesn't re-parse existing children or destroy their event listeners.
  • Use a DocumentFragment to batch-build many nodes and insert them in a single operation — this minimises browser reflows for better performance.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel