The DOM is the browser’s tree of HTML nodes. Select with querySelector / querySelectorAll, create nodes with createElement, and set textContent unless you intentionally parse HTML. Bind events on a stable parent when lists re-render.
This JavaScript cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- Select one:
document.querySelector(".item")— first match ornull. - Select all:
querySelectorAllreturns a static NodeList. Spread to array if you needmap. - Create:
const el = document.createElement("button")thenappend. - Text:
textContentis safe.innerHTMLparses markup and can run XSS. - classList:
add,remove,toggle,contains— do not concatenate className strings. - Attrs:
getAttribute/setAttribute/dataset.foofordata-foo. - Traverse:
parentElement,closest,children,nextElementSibling. - Ready:
deferscripts see a complete DOM. Otherwise listen toDOMContentLoaded.
Copy-paste examples
Safe list render
Clear with replaceChildren, not innerHTML = "" plus string concat from the API.
function renderNames(host, names) {
const items = names.map((name) => {
const li = document.createElement('li');
li.textContent = name;
return li;
});
host.replaceChildren(...items);
}
document.querySelector('#add').addEventListener('click', () => {
document.querySelector('#panel').classList.toggle('is-open');
});Common mistakes
- Using
innerHTMLwith server or user strings. getElementByIdthen forgetting the element can benull.- Querying inside a loop (
querySelectorper row) instead of caching or delegating. - Mixing jQuery snippets with vanilla without knowing
$is not on the page.
FAQ
- querySelector vs getElementById?
getElementByIdis slightly simpler for ids.querySelectorhandles every CSS selector. Both are fine.
- Live HTMLCollection vs NodeList?
getElementsByClassNameis live and can surprise you during loops.querySelectorAllis static.
- Do I need React to touch the DOM? No. Small pages should use the DOM APIs directly. React is for component state at scale.
Related JavaScript cheat sheets
- Javascript Cheat Sheet 2026
- Javascript Array Methods Cheat Sheet
- Javascript String Methods Cheat Sheet
Build with this stack
When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds custom web development and also sells ready-made source code. Request a quote and tell us the stack.
Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.