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.
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:
data-* attributes and standard HTML attributes.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:
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>
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 |
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:
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
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:
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:
// ── 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>`);
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");
Key Method Reference
These are the core DOM manipulation methods you'll use in virtually every project. Bookmark this list:
el as the last child of
parent. Accepts multiple nodes and strings.
removeChild.src,
href, aria-*, or custom attributes.
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:
<html> or
<body>
to switch between light and dark themes instantly.
<li> items as users add entries
to a to-do list, shopping cart, or tag list.<img> element's src
attribute to swap photos in a gallery or carousel.<div>, append it with a message and
class,
then remove it after a timeout..error classes on inputs and inject
validation messages next to fields dynamically.textContent on each event to
show real-time numbers without re-rendering the whole page.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.
Common Patterns & Recipes
These are practical DOM manipulation patterns you'll reach for constantly in real JavaScript projects:
// ── 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
classList.toggle("active") do when the class is
already present?
- 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
datasetobject withdata-*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
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.