Skip to content
jshacks.dev
Browser

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.

8 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, NGINX, Postman and Swagger logos.

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.

select.jsJavaScript
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));
Text
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.

closest.jsJavaScript
const link = document.querySelector("li a");
console.log(link.closest("ul").id, link.matches("a[href]"));
Text
list true

Properties that start with element or children skip text nodes, which makes them the ones you want.

tree.jsJavaScript
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);
Text
2
One
Two
Two
list

childNodes, 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.

create.jsJavaScript
const li = document.createElement("li");
li.className = "item";
li.textContent = "Three";
li.dataset.id = "3";

console.log(li.outerHTML);
Text
<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.

insert.jsJavaScript
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);
Text
5
Zero

Strings 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.

clone.jsJavaScript
const copy = document.querySelector("li").cloneNode(true);
console.log(copy.textContent, copy.isConnected);
Text
One false

Remove and replace

remove() removes an element from the page. replaceChildren() with no arguments removes all children, and with arguments replaces them.

remove.jsJavaScript
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);
Text
1
1
0

Text 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.

text.jsJavaScript
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);
Text
Hello world
Hello <b>world</b>
&lt;b&gt;not bold&lt;/b&gt;

Classes

classList has add, remove, toggle, contains and replace. The toggle method takes an optional second argument that forces the state.

classes.jsJavaScript
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"));
Text
card open true

Attributes 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.

attrs.jsJavaScript
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);
Text
start typed
true

Data attributes

Attributes starting with data- are exposed through dataset, converted from kebab-case to camelCase. Values are always strings.

dataset.jsJavaScript
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);
Text
42 42 string
false

Styles

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.

styles.jsJavaScript
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();
Text
red 8px
block

Prefer 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.

geometry.jsJavaScript
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);
Text
number number true
true true

Scrolling and focus

scrollIntoView scrolls an element into view, with options for smooth behavior. focus() moves keyboard focus, and preventScroll: true avoids the jump.

scroll.jsJavaScript
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);
Text
true

Events

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(...).

events.jsJavaScript
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();
Text
clicked One

Aborting 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.

forms.jsJavaScript
const form = document.querySelector("form");
const data = new FormData(form);

console.log(Object.fromEntries(data));
console.log(form.elements.email.value, form.checkValidity());
Text
{ email: '[email protected]', plan: 'pro' }
[email protected] true

Templates

A <template> holds inert markup. Clone its content to stamp out repeated structures without building them by string.

template.jsJavaScript
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);
Text
1

Observers

Three observers cover most needs. MutationObserver reports changes to the DOM. IntersectionObserver reports visibility. ResizeObserver reports size changes.

observers.jsJavaScript
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"));
Text
childList 1

Mutation 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.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.