Skip to content
Velloreth
Web Development 5 min read

JavaScript DOM Manipulation: A Practical Guide

The DOM is the page as a tree. Learn the selection, the creation, the update, the events, and the performance traps.

By

The tree

<div id="app">
  <h1>Title</h1>
  <ul>
    <li>One</li>
  </ul>
</div>

The DOM is a tree of nodes.

JavaScript reads and changes the tree, and the browser re-renders the affected part.

The selection

const app = document.getElementById('app');
const first = document.querySelector('.item');
const all = document.querySelectorAll('.item');
const items = document.getElementsByClassName('item');
MethodReturnsLive
getElementByIdone elementno
querySelectorthe first matchno
querySelectorAlla static NodeListno
getElementsByClassNamean HTMLCollectionyes

A live collection updates as the DOM changes, which is a common source of a bug in a loop.

The creation

const li = document.createElement('li');
li.textContent = 'Two';
li.classList.add('item');
li.dataset.id = '2';

document.querySelector('ul').append(li);

createElement makes a node.

append adds it, and prepend adds it first.

remove deletes it.

cloneNode(true) copies it with the children.

The update

el.textContent = 'New text';        // safe
el.innerHTML = '<b>Bold</b>';       // parses HTML
el.setAttribute('aria-label', 'x');
el.classList.toggle('active');
el.style.color = 'red';

textContent is safer than innerHTML for untrusted text.

innerHTML parses the string as HTML, so a script in the string can execute.

classList is cleaner than a string manipulation of className.

The batch

// Slow: a reflow per append
items.forEach((item) => list.append(makeLi(item)));

// Fast: one reflow
const fragment = document.createDocumentFragment();
items.forEach((item) => fragment.append(makeLi(item)));
list.append(fragment);

A batch of changes in one reflow is faster than many.

Read the layout values together and write them together, because a read after a write forces a reflow.

// Slow: read, write, read, write
el.style.width = el.offsetWidth + 10 + 'px';

// Fast: read, then write
const width = el.offsetWidth;
el.style.width = width + 10 + 'px';

The events

button.addEventListener('click', (event) => {
  event.preventDefault();
  console.log(event.target);
});

event.target is the element that fired the event.

event.currentTarget is the element the listener is attached to.

preventDefault stops the default action.

stopPropagation stops the bubbling.

Event delegation

list.addEventListener('click', (event) => {
  const item = event.target.closest('li');
  if (!item) return;
  console.log(item.dataset.id);
});

One listener on a parent instead of one per child.

It works because an event bubbles.

It handles a child added later without a new listener.

The performance

A large list is slow to render, so virtualise it: render only the visible rows.

A frequent event such as a scroll or a resize should be throttled or debounced.

A layout read in a loop is a reflow per iteration.

A mutation observer watches for a change without polling.

new MutationObserver(callback).observe(el, { childList: true });

The security

Never insert untrusted text with innerHTML.

// Vulnerable
el.innerHTML = userComment;

// Safe
el.textContent = userComment;

A sanitizer is required if HTML is genuinely needed.

A URL from a user must be validated, because javascript: is a script.

The rendering pipeline

A DOM change does not paint immediately, and understanding the pipeline explains why a batch is faster. The browser parses the HTML into the DOM, applies the CSS into a render tree, calculates the geometry in a layout pass, and paints the pixels. A change to a class or a text node invalidates part of the tree, and the browser schedules a layout and a paint. A read of a layout property such as offsetWidth forces the browser to run the layout immediately, because the value must be current, and a read after a write in a loop therefore forces a layout per iteration. The fix is to read every value first, then write every value, so the browser runs one layout. A change that only affects a paint, such as a colour, skips the layout, which is why an animation on transform and opacity is cheap and an animation on width is expensive.

The framework question

A framework exists because manual DOM manipulation is error-prone at scale, and knowing when to use one is a judgement rather than a rule. A small page with a few interactions is simpler with direct DOM code, because there is no build step and no abstraction to learn. A page with a large amount of state that changes in several places is easier with a framework, because the framework derives the DOM from the state and the developer does not track which node to update. The middle ground is a small library that handles one concern, such as a template or a reactive binding. The signal that a framework is warranted is a bug caused by the DOM and the state disagreeing, because that is the class of bug a framework removes.

Common mistakes

innerHTML with user input. An XSS.

A live collection in a loop. An infinite loop.

A reflow per append. A slow render.

A read after a write in a loop. A forced reflow.

A listener per row. A memory leak.

No preventDefault. A page reload.

A querySelector in a loop. A repeated lookup.

A detached node kept in a variable. A memory leak.

A setTimeout in a scroll handler. A jank.

No cleanup on unmount. A leak.

A quotable summary

The DOM is a tree of nodes that the browser renders, and JavaScript reads and changes it with querySelector, createElement and textContent. A batch of changes in one reflow is much faster than many, textContent is safer than innerHTML for untrusted text, and event delegation attaches one listener to a parent instead of one per child. Read the layout values together and write them together, because a read after a write forces a reflow.

For the related topics, see event-delegation-explained and javascript-array-methods-guide. For the broader context, javascript-performance-tips and javascript-debugging-console.

Frequently asked questions

What is the DOM?
The Document Object Model, a tree of nodes that represents the page. JavaScript reads and changes the tree, and the browser re-renders the affected part. It is an API over the parsed HTML, not the HTML text itself.
What is the difference between querySelector and getElementById?
querySelector takes any CSS selector and returns the first match, and getElementById takes an id and is slightly faster. querySelectorAll returns a static NodeList, and getElementsByClassName returns a live HTMLCollection that updates as the DOM changes.
Why is innerHTML dangerous?
Because it parses the string as HTML, so a script in the string can execute. That is a cross-site scripting vulnerability when the string contains user input. Use textContent for text, and sanitise the input if HTML is genuinely needed.
What is a reflow?
The browser recalculating the layout after a change to the DOM or the styles. It is expensive, so a batch of changes in one reflow is much faster than many separate changes. Read the layout values together and write them together.
What is event delegation?
Attaching one listener to a parent element instead of one per child, and using the event target to find the child. It works because an event bubbles, and it handles a child added later without a new listener.
What is a DocumentFragment?
A lightweight container that is not part of the document. You append the nodes to it and then append the fragment once, which causes a single reflow instead of one per node.