DOM Manipulation
Learn to read and modify the DOM — create, update, and remove elements with JS.
What you'll learn
- How to select elements with querySelector and querySelectorAll
- Creating and appending elements with createElement and appendChild
- Updating content with textContent and innerHTML (and the difference)
- Removing and replacing elements in the DOM tree
Concept
DOM Manipulation
The DOM (Document Object Model) is the browser's live, in-memory representation of your HTML page. JavaScript can read and modify this tree — change text, add elements, update attributes, alter styles — and the browser re-renders instantly. This is how every dynamic web feature works: a todo list adds items, a search filters results, a modal opens and closes.
Selecting Elements
Before you can manipulate an element, you must find it. The two primary methods are:
document.querySelector(selector)— returns the first matching element (ornull). Uses CSS selector syntax:.card,#header,nav a.document.querySelectorAll(selector)— returns a NodeList of all matches. Iterate with.forEach()or convert to an array withArray.from().
These replace the older getElementById, getElementsByClassName, and getElementsByTagName. The querySelector methods are more flexible because they accept any CSS selector.
Creating Elements
To add new content, create an element with document.createElement(tagName), configure it, then insert it into the DOM:
const li = document.createElement("li");
li.textContent = "New item";
li.className = "list-item";
document.querySelector("ul").appendChild(li);
appendChild adds the element as the last child. Use prepend, insertBefore, or insertAdjacentHTML for other positions.
textContent vs. innerHTML
textContent sets the text of an element — it is safe from XSS because the content is treated as plain text. innerHTML sets the HTML markup — it can insert elements, but it is dangerous with user input because it can execute injected scripts (XSS). Use textContent when you only need text. Use innerHTML only with trusted, sanitized content — never with raw user input.
Removing Elements
To remove an element, call element.remove(). To replace one element with another, use parent.replaceChild(newEl, oldEl). These operations update the DOM immediately, and the browser re-renders. For performance with large lists, consider batching changes or using a DocumentFragment to avoid multiple reflows.
Example
// Building a dynamic todo list with DOM manipulation
const input = document.querySelector("#todo-input");
const list = document.querySelector("#todo-list");
const button = document.querySelector("#add-btn");
button.addEventListener("click", () => {
const text = input.value.trim();
if (!text) return;
// Create the list item
const li = document.createElement("li");
li.className = "todo-item";
// Create a span for the text (safe from XSS)
const span = document.createElement("span");
span.textContent = text; // NOT innerHTML — prevents XSS
// Create a delete button
const del = document.createElement("button");
del.textContent = "Delete";
del.addEventListener("click", () => li.remove());
// Assemble and insert
li.append(span, del);
list.appendChild(li);
// Reset the input
input.value = "";
});
createElement builds new DOM nodes. textContent safely sets text without XSS risk. append inserts multiple children at once. The delete button calls li.remove() to remove the item. Every interaction updates the DOM and the browser re-renders instantly.
Try it
- Markdown Previewer
This tool manipulates the DOM in real time as you type — watch the preview update.
- HTML Entity Encoder
Encoding entities is essential when inserting user text into the DOM safely.
Common mistakes
The mistake
Using innerHTML with user input, creating an XSS vulnerability.
The fix
Use textContent for any text that comes from the user. It treats the input as plain text, not HTML. Only use innerHTML with trusted, sanitized content — never with raw user strings.
The mistake
Calling document.querySelector before the element exists in the DOM.
The fix
Place your <script> at the end of <body>, or wrap your code in a DOMContentLoaded event listener. Otherwise querySelector returns null and your code throws when you try to use the result.
Related Resources
Related Snippets
- JavaScript Array Methods
Array methods for transforming data before rendering it to the DOM.
Related Cheatsheets
- JavaScript Cheatsheet
Reference for DOM methods: querySelector, createElement, append, remove.
Practice DOM Manipulation
8 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.