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 Velloreth
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');
| Method | Returns | Live |
|---|---|---|
getElementById | one element | no |
querySelector | the first match | no |
querySelectorAll | a static NodeList | no |
getElementsByClassName | an HTMLCollection | yes |
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.
Related reading
For the related topics, see event-delegation-explained and javascript-array-methods-guide. For the broader context, javascript-performance-tips and javascript-debugging-console.