DOM Manipulation
The Document Object Model (DOM) is a tree of objects representing your HTML. JavaScript gives you a rich API to select, create, modify, and remove elements — the foundation of all interactive web UIs.
How do you change HTML with JavaScript?
Select elements with document.querySelector("css selector") or querySelectorAll, then change them: textContent for text, classList.add/remove/toggle for styling, setAttribute for attributes, and append/remove to add or delete elements. Create new elements with document.createElement.
const title = document.querySelector("h1");
title.textContent = "Updated!";
title.classList.add("highlight");
const li = document.createElement("li");
li.textContent = "New item";
document.querySelector("ul").append(li);
document.querySelectorAll(".card").forEach((c) => c.remove());Selecting Elements
getElementById('id')— Exact ID — fastest lookupquerySelector('css')— First match for any CSS selectorquerySelectorAll('css')— All matches → static NodeListgetElementsByClassName('c')— Live HTMLCollection by classgetElementsByTagName('tag')— Live HTMLCollection by tagel.closest('.cls')— Walk up tree to first matching ancestorel.matches('selector')— Test if element matches selectorModifying Elements
el.textContent = '...'— Safe text — escapes HTML special charsel.innerHTML = '...'— Parse & render HTML — sanitize first!el.classList.add/remove/toggle— Manage CSS classes safelyel.style.property = value— Set inline styles (camelCase)el.setAttribute('key', 'val')— Set any HTML attributeel.dataset.key = value— Set data-* attribute via datasetel.remove()— Remove element from DOMPerformance Tips
Batch DOM writes
Group DOM mutations together. Alternating reads and writes cause multiple reflows. Read all values first, then write all changes.
Use DocumentFragment
When creating many elements, append them to a DocumentFragment first, then add the fragment to the DOM in one operation.
Cache DOM queries
Store querySelector results in variables. Re-querying the DOM on every event is wasteful — cache once, use many times.
Common Pitfalls
Interactive Counter Demo
Code Editor
<input id="item" placeholder="New task">
<button id="add">Add</button>
<ul id="list"><li>Learn the DOM</li></ul>Preview
DOM manipulation — core concepts
Querying — getElementById vs querySelector
getElementById('id') is the fastest (O(1) hash lookup). querySelector('.class') uses CSS selector syntax and is flexible. querySelectorAll returns a static NodeList — a snapshot. getElementsByClassName returns a live HTMLCollection that auto-updates.
🎯 Quick Check
Which returns a live (auto-updating) collection of DOM elements?
DOM Manipulation: summary
Key points
- Prefer
textContentoverinnerHTMLfor text;innerHTMLwith user input is an XSS risk. - Toggle CSS classes rather than setting many inline
styleproperties. querySelectorAllreturns a static NodeList that supportsforEach.- Batch DOM changes, for example with a
DocumentFragment, when inserting many elements.
Frequently asked questions
›Why does querySelector return null?
Either the selector doesn't match anything, or the script ran before the element existed. Load the script with defer or at the end of <body>.
›What is the difference between innerHTML and textContent?
innerHTML parses a string as HTML; textContent sets plain text and is faster and safe from injected HTML.