DOM Manipulation Cheat Sheet
A DOM manipulation cheat sheet: select, create, insert, move, remove, classes, attributes, data, styles, events, forms, scrolling and observers, with examples.

This is a reference for the DOM methods you use every day, grouped by task, with a short example and the result for each. It is meant to be skimmed and copied from, not read from top to bottom. Every example runs in a current browser, and each group links back to the standard it comes from: the DOM Living Standard and MDN's DOM reference. Examples assume a small page with a list, a heading and a form, and the output blocks show what you would see in the console. Where two methods look alike, the difference is called out in a sentence, since that is where mistakes happen.
Select elements
querySelector returns the first match or null; querySelectorAll returns a static NodeList. Use getElementById when you have an id, as it is the simplest and fastest.
const first = document.querySelector("li");
const all = document.querySelectorAll("li.item");
const byId = document.getElementById("list");
const within = byId.querySelector("a");
console.log(first.tagName, all.length, byId.id, within?.href);
console.log([...all].map((li) => li.textContent));LI 2 list https://example.com/a
[ 'One', 'Two' ]A NodeList from querySelectorAll does not update when the page changes, and it has forEach, but not map, so spread it into an array first. Use closest(selector) to walk up to the nearest ancestor that matches, and matches(selector) to test an element.
const link = document.querySelector("li a");
console.log(link.closest("ul").id, link.matches("a[href]"));list trueNavigate the tree
Properties that start with element or children skip text nodes, which makes them the ones you want.
const list = document.querySelector("#list");
console.log(list.children.length);
console.log(list.firstElementChild.textContent);
console.log(list.lastElementChild.textContent);
console.log(list.firstElementChild.nextElementSibling.textContent);
console.log(list.firstElementChild.parentElement.id);2
One
Two
Two
listchildNodes, firstChild and nextSibling include whitespace text nodes, and are rarely what you need.
Create elements
createElement makes an element, and createTextNode makes text. Setting textContent is usually shorter than creating a text node.
const li = document.createElement("li");
li.className = "item";
li.textContent = "Three";
li.dataset.id = "3";
console.log(li.outerHTML);<li class="item" data-id="3">Three</li>Insert and move
append and prepend add nodes or strings inside an element, at the end or start. before and after add siblings. replaceWith swaps an element. Inserting a node that is already in the page moves it rather than copying.
const list = document.querySelector("#list");
const item = document.createElement("li");
item.textContent = "Zero";
list.prepend(item);
list.append("Plain text", document.createElement("li"));
list.firstElementChild.after(document.createElement("hr"));
console.log(list.children.length);
console.log(list.firstElementChild.textContent);5
ZeroStrings passed to append become text nodes, not HTML, so they are safe. For HTML at a position, use insertAdjacentHTML, only with trusted markup. cloneNode(true) makes a deep copy, which does not copy event listeners.
const copy = document.querySelector("li").cloneNode(true);
console.log(copy.textContent, copy.isConnected);One falseRemove and replace
remove() removes an element from the page. replaceChildren() with no arguments removes all children, and with arguments replaces them.
const list = document.querySelector("#list");
list.firstElementChild.remove();
console.log(list.children.length);
list.replaceChildren(document.createElement("li"));
console.log(list.children.length);
list.replaceChildren();
console.log(list.children.length);1
1
0Text and HTML
textContent reads or sets all the text, treating input as plain text. innerText respects CSS and layout, so hidden text is skipped and line breaks follow the rendering, but it forces layout. innerHTML reads or sets markup and parses it, which is unsafe with untrusted input.
const p = document.createElement("p");
p.innerHTML = "Hello <b>world</b>";
console.log(p.textContent);
console.log(p.innerHTML);
p.textContent = "<b>not bold</b>";
console.log(p.innerHTML);Hello world
Hello <b>world</b>
<b>not bold</b>Classes
classList has add, remove, toggle, contains and replace. The toggle method takes an optional second argument that forces the state.
const box = document.createElement("div");
box.classList.add("card", "active");
box.classList.toggle("active");
box.classList.toggle("open", true);
console.log(box.className, box.classList.contains("card"));card open trueAttributes and properties
getAttribute, setAttribute, removeAttribute and hasAttribute work with the HTML attribute. Properties such as value, checked and href reflect the live state, and they do not always match the attribute: an input's value attribute is its default, while the value property is what is currently typed.
const input = document.createElement("input");
input.setAttribute("value", "start");
input.value = "typed";
console.log(input.getAttribute("value"), input.value);
input.toggleAttribute("disabled", true);
console.log(input.disabled);start typed
trueData attributes
Attributes starting with data- are exposed through dataset, converted from kebab-case to camelCase. Values are always strings.
const el = document.createElement("div");
el.dataset.userId = "42";
el.dataset.active = "true";
console.log(el.getAttribute("data-user-id"), el.dataset.userId, typeof el.dataset.active);
delete el.dataset.active;
console.log("active" in el.dataset);42 42 string
falseStyles
Set a style property directly, or set a CSS custom property with style.setProperty. Reading computed values goes through getComputedStyle, which includes values from stylesheets.
const box = document.createElement("div");
document.body.append(box);
box.style.color = "red";
box.style.setProperty("--gap", "8px");
console.log(box.style.color, box.style.getPropertyValue("--gap"));
console.log(getComputedStyle(box).display);
box.remove();red 8px
blockPrefer toggling classes over setting many inline styles, because it keeps styling in the stylesheet.
Size and position
getBoundingClientRect() returns the position and size relative to the viewport. offsetWidth and clientHeight give layout sizes as integers. Reading these forces layout, so batch reads before writes.
const rect = document.querySelector("h1").getBoundingClientRect();
console.log(typeof rect.top, typeof rect.width, rect.height > 0);
console.log(window.innerWidth > 0, document.documentElement.scrollHeight > 0);number number true
true trueScrolling and focus
scrollIntoView scrolls an element into view, with options for smooth behavior. focus() moves keyboard focus, and preventScroll: true avoids the jump.
const target = document.querySelector("#section");
target.scrollIntoView({ behavior: "smooth", block: "start" });
const button = document.querySelector("button");
button.focus({ preventScroll: true });
console.log(document.activeElement === button);trueEvents
addEventListener takes a type, a handler and options such as once, passive and signal. Use event delegation for lists: attach one listener to the parent and check event.target.closest(...).
const list = document.querySelector("#list");
const controller = new AbortController();
list.addEventListener(
"click",
(event) => {
const li = event.target.closest("li");
if (li && list.contains(li)) console.log("clicked", li.textContent);
},
{ signal: controller.signal }
);
list.firstElementChild.click();
controller.abort();
list.firstElementChild.click();clicked OneAborting the signal removes the listener, which is the tidy way to clean up many at once. Dispatch your own events with new CustomEvent("name", { detail, bubbles: true }).
Forms
FormData reads all fields of a form. form.elements gives named access. checkValidity() and reportValidity() use the built-in constraints.
const form = document.querySelector("form");
const data = new FormData(form);
console.log(Object.fromEntries(data));
console.log(form.elements.email.value, form.checkValidity());{ email: '[email protected]', plan: 'pro' }
[email protected] trueTemplates
A <template> holds inert markup. Clone its content to stamp out repeated structures without building them by string.
const template = document.querySelector("#row");
const row = template.content.firstElementChild.cloneNode(true);
row.querySelector(".name").textContent = "Ada";
document.querySelector("tbody").append(row);
console.log(document.querySelectorAll("tbody tr").length);1Observers
Three observers cover most needs. MutationObserver reports changes to the DOM. IntersectionObserver reports visibility. ResizeObserver reports size changes.
const observer = new MutationObserver((records) => {
console.log(records[0].type, records[0].addedNodes.length);
});
observer.observe(document.querySelector("#list"), { childList: true });
document.querySelector("#list").append(document.createElement("li"));childList 1Mutation callbacks run asynchronously in a microtask after the change, so the log appears after the current code finishes.
Habits that prevent bugs
Select once and keep the reference, rather than querying in loops. Batch reads of layout together before any writes. Use textContent and property assignment for data, classList for state and delegation for lists. Check that elements exist before using them, since querySelector returns null when nothing matches, and the resulting TypeError is the most common DOM error. And clean up listeners and observers when the element goes away.
Reading the cheat sheet well
A reference is most useful when you know how the pieces fit, so here are the patterns behind the lists. Almost everything in the DOM is either a query, a change or a notification. Queries find nodes: querySelector, closest and the tree properties. Changes create, move, remove and modify nodes: createElement, append, remove, classList, attributes and textContent. Notifications tell you something happened: events and the three observers. When you are stuck on a task, ask which of the three you need, and the right section of this sheet is usually obvious.
Two habits save the most debugging time. First, treat every query result as possibly missing. A null from querySelector is the most common cause of a "cannot read properties of null" error, and the cause is usually timing: the script ran before the markup existed, so load scripts with defer or run the code after DOMContentLoaded. Second, keep reads and writes apart. Reading offsetHeight forces the browser to calculate layout, and writing a style invalidates it, so a loop that alternates between them makes the browser recalculate over and over. Read everything you need first, then write.
Finally, remember that the DOM is a live structure with a cost. Large batches of changes are best made on a detached element or a fragment and inserted once, while changes that the user will see should be tied to requestAnimationFrame so they land on a frame boundary. Most pages never need more than the methods listed here, and when you do reach for something unfamiliar, the specification and MDN are the sources to trust.


