All topics
DOMbeginner

DOM Manipulation Basics

Selecting, creating, modifying, and removing elements from the live document tree using core DOM APIs.

The DOM (Document Object Model) is the browser's live, tree-structured representation of an HTML document, and manipulating it directly with JavaScript is the foundation everything else — frameworks, virtual DOM diffing, reactive rendering — is ultimately built on top of. Even in a framework-heavy job, interviewers check for raw DOM fluency because it reveals whether you understand what's actually happening underneath the abstraction.

The DOM is like a building's live floor plan blueprint that also happens to be the actual building — walking up and modifying a wall (element) via querySelector immediately changes the real physical structure, which is why builders (browsers) try to batch several wall changes together before recalculating the whole building's structural integrity (reflow) instead of doing it after every single nail.

Key Concepts

1
Selecting elements is the starting point: document.querySelector(selector) returns the first matching element for any valid CSS selector, document.querySelectorAll(selector) returns a static NodeList of every match, and older methods like getElementById/getElementsByClassName still exist and return live collections in some cases, which behave slightly differently from the static NodeList returned by querySelectorAll.
document.querySelector(selector)document.querySelectorAll(selector)NodeListgetElementByIdgetElementsByClassName
2
Creating and modifying nodes involves document.createElement(tagName) to make a new, detached element, followed by setting properties like .textContent, .innerHTML (which parses and injects raw HTML — a genuine XSS risk if the content includes unsanitized user input), or .className/.classList for styling, and finally attaching it to the visible tree with parentNode.appendChild(newNode) or the more flexible parentNode.insertBefore()/element.append()/element.prepend(). Removing a node uses element.remove() (modern) or the older parentNode.removeChild(element).
document.createElement(tagName).textContent.innerHTML.className.classList
3
Because every DOM read or write can potentially trigger the browser to recalculate layout (a 'reflow') or repaint pixels, batching DOM changes — building up a structure in memory (or using a DocumentFragment) before a single attachment to the live tree — is significantly more performant than making many small, individual live-DOM mutations in a loop, especially for anything rendering large lists or frequently-updating UI.
DocumentFragment