DOM & Browser APIs

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 lookup
querySelector('css')— First match for any CSS selector
querySelectorAll('css')— All matches → static NodeList
getElementsByClassName('c')— Live HTMLCollection by class
getElementsByTagName('tag')— Live HTMLCollection by tag
el.closest('.cls')— Walk up tree to first matching ancestor
el.matches('selector')— Test if element matches selector

Modifying Elements

el.textContent = '...'— Safe text — escapes HTML special chars
el.innerHTML = '...'— Parse & render HTML — sanitize first!
el.classList.add/remove/toggle— Manage CSS classes safely
el.style.property = value— Set inline styles (camelCase)
el.setAttribute('key', 'val')— Set any HTML attribute
el.dataset.key = value— Set data-* attribute via dataset
el.remove()— Remove element from DOM

Performance 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

Setting innerHTML with user input — XSS vulnerability
Use textContent for user data, or sanitize with DOMPurify before innerHTML
Querying the DOM before the document is ready
Put scripts at end of body, or use DOMContentLoaded event, or defer attribute
Modifying live NodeLists/HTMLCollections while iterating
Convert to array first: [...document.querySelectorAll('.item')]
Forcing layout thrashing — read/write DOM in alternating loop
Batch all reads, then batch all writes to avoid multiple reflows

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

1 / 4
1

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.

1 of 4
⚠️Avoid innerHTML with user content
Never set innerHTML to user-provided strings — it executes embedded scripts and creates XSS vulnerabilities. Use textContent for plain text. Use DOMPurify to sanitize HTML if you must render user-provided markup.

🎯 Quick Check

Which returns a live (auto-updating) collection of DOM elements?

DOM Manipulation: summary

Key points

  • Prefer textContent over innerHTML for text; innerHTML with user input is an XSS risk.
  • Toggle CSS classes rather than setting many inline style properties.
  • querySelectorAll returns a static NodeList that supports forEach.
  • 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.