JavaScriptMedium
What is DOM manipulation?
DOM manipulation means using JavaScript to create, change, move or remove elements, attributes, text and styles on the page after it has loaded.
Core operations
- Create:
document.createElement("li"),document.createTextNode(text), or<template>cloning. - Insert:
parent.append(...nodes),prepend,before,after,replaceWith,insertAdjacentHTML/Element. - Remove:
element.remove(). - Content:
textContent(safe for text) orinnerHTML(parses HTML, an XSS risk with user input). - Attributes:
setAttribute,getAttribute,removeAttribute,toggleAttribute, anddatasetfordata-*attributes. - Classes and styles:
classList.add/remove/toggle,element.style.setProperty.
Doing it efficiently
- Batch DOM writes: build many nodes in a
DocumentFragment(or an array passed to oneappend) and insert once. - Avoid layout thrashing: do not alternate reading layout (
offsetHeight) and writing styles in a loop. - Prefer classes over inline styles so CSS controls appearance.
- Use event delegation instead of a listener per item.
- Animate with CSS transforms/opacity, not layout properties.
Safety
Never insert untrusted strings with innerHTML. Use textContent, or sanitise with a library like DOMPurify, or the newer setHTML Sanitizer API where supported.
Frameworks vs manual
Frameworks are better for complex, state-driven UIs. Direct manipulation is still right for small widgets, progressive enhancement and performance-critical spots.
Code example
js
1document.body.innerHTML = `<h2>Tasks</h2><ul id="tasks"></ul><button id="add">Add 3 tasks</button>`;2const list = document.getElementById("tasks");34function renderTasks(titles) {5 // Build off-screen, insert once (one layout instead of N)6 const fragment = document.createDocumentFragment();7 for (const title of titles) {8 const li = document.createElement("li");9 li.textContent = title; // safe: never parses HTML10 li.dataset.status = "todo";11 li.classList.add("task");12 fragment.append(li);13 }14 list.append(fragment);15}1617renderTasks(["Write docs", "Fix bug", "<img src=x onerror=alert(1)>"]); // the last one stays plain text18console.log(list.children.length, list.lastElementChild.textContent); // 3 "<img src=x onerror=alert(1)>"1920document.getElementById("add").addEventListener("click", () => renderTasks(["A", "B", "C"]));2122// Update, move and remove23const first = list.firstElementChild;24first.dataset.status = "done";25first.classList.toggle("done", true);26list.append(first); // moves it to the end (no copy)27list.querySelector('[data-status="todo"]').remove();28console.log([...list.children].map((li) => `${li.textContent}:${li.dataset.status}`));
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.