JavaScript DOM Cheat Sheet

Select elements, handle events with addEventListener and delegation, and work with classes, forms, localStorage, and fetch. The mental models behind the DOM, in one scannable reference. You can also download the information as a printable cheat sheet:

Free Bonus: JavaScript DOM Cheat Sheet

Get the JavaScript DOM Cheat Sheet (PDF), a printable reference to querySelector, addEventListener and event delegation, classList, creating elements, forms and FormData, localStorage, and fetch from the browser:

JavaScript DOM Cheat Sheet

Want a guided path instead of a reference? Start learning at realjs.com.

Getting Started

  • The DOM is the browser’s live tree of the page
  • Change the DOM and the browser redraws the page to match
  • defer and module scripts run once the HTML is parsed
Language: HTML Filename: Run Code After the HTML Loads
<script defer src="app.js"></script>
<script type="module" src="m.js"></script>
Language: HTML Filename: The Page Used Below
<h1 id="title">To-Do</h1>
<ul id="todos">
  <li data-id="1">Read</li>
  <li data-id="2" class="done">Code</li>
</ul>
<button id="add">Add</button>

Select Elements

  • querySelector() takes any CSS selector and returns the first match or null
  • querySelectorAll() returns a static NodeList that has forEach() but not map()
Language: JavaScript Filename: Query With CSS Selectors
const $ = (s) => document.querySelector(s);
$("#title");             // <h1 id="title">
$("#todos > .done");     // Second <li>
$("[data-id='1']");      // First <li>
$("#nope");              // null
document.getElementById("title");
Language: JavaScript Filename: Select Many & Walk the Tree
const lis = document.querySelectorAll("li");
lis.length;              // 2
[...lis].map((li) => li.textContent);
// ["Read", "Code"]
const li = lis[0];
li.parentElement.id;     // "todos"
li.nextElementSibling;   // Second <li>
li.closest("ul");        // <ul id="todos">

Change Elements

  • Set text with textContent, which never parses HTML
  • Use innerHTML only with trusted strings, since it can run injected code
  • Prefer toggling classes over setting inline styles
Language: JavaScript Filename: Text, HTML & Styles
const h1 = document.querySelector("h1");
h1.textContent;               // "To-Do"
h1.textContent = "<b>Hi</b>"; // Literal text
h1.innerHTML = "<b>Hi</b>";   // Bold "Hi"
h1.style.color = "tomato";
Language: JavaScript Filename: Attributes & Data
const btn = document.querySelector("#add");
btn.title = "New task";       // Property
btn.getAttribute("title");    // "New task"
btn.setAttribute("aria-label", "Add");
li.dataset.id;                // "1"
li.dataset.dueDate = "mon"; // data-due-date
Language: JavaScript Filename: Classes With classList
li.classList.add("done", "new");
li.classList.remove("new");
li.classList.toggle("done");  // false
li.classList.toggle("done", true); // true
li.classList.contains("done");     // true
li.classList.replace("done", "todo");

Create & Remove

  • New elements stay off the page until you insert them
  • Inserting an element that’s already on the page moves it
Language: JavaScript Filename: Create & Insert
const ul = document.querySelector("#todos");
const item = document.createElement("li");
item.textContent = "Ship";
ul.append(item);         // Last child
ul.prepend(item);        // Moves it first
item.remove();           // Off the page

Events With addEventListener

  • addEventListener() lets many handlers share one event
  • event.target is the element the event started on, and event.currentTarget is the one with the listener
  • To remove a listener, pass the same event, function, and capture option
Language: JavaScript Filename: Listen for Clicks
btn.addEventListener("click", (event) => {
  console.log(event.type);    // "click"
  console.log(event.target);  // <button>
});
Language: JavaScript Filename: Options & Removal
const onKey = (e) => console.log(e.key);
window.addEventListener("keydown", onKey);
window.removeEventListener("keydown", onKey);
const save = () => console.log("Saved");
btn.addEventListener("click", save, {
  once: true,  // Runs once, then removed
});
Event Fires when
click Element is clicked or tapped
input The user edits a field
submit A form is submitted

Event Delegation

  • Most events bubble up from the target through every ancestor
  • One listener on a parent handles current and future children
  • Use closest(), since target may be a nested element
Language: JavaScript Filename: Handle Clicks on Any Item
ul.addEventListener("click", (event) => {
  const li = event.target.closest("li");
  if (!li) return;
  li.classList.toggle("done");
  console.log(li.dataset.id);  // e.g. "1"
});

Forms

  • Listen for submit, not a button click, so Enter works too
  • A field’s value is always a string
  • FormData skips unchecked boxes and fields without a name
Language: HTML Filename: A Simple Form
<form id="signup">
  <input name="email" type="email" required>
  <input name="age" type="number">
  <input name="news" type="checkbox">
  <button>Sign Up</button>
</form>
Language: JavaScript Filename: Handle Submit
const form = document.querySelector("form");
form.addEventListener("submit", (event) => {
  event.preventDefault();  // Stay on page
  const data = new FormData(form);
  console.log(Object.fromEntries(data));
  // { email: "[email protected]", age: "36",
  //   news: "on" }
});
Language: JavaScript Filename: Read Fields
// Once the user fills in the form:
const { email, age, news } = form.elements;
email.value;             // "[email protected]"
age.value;               // "36"
age.valueAsNumber;       // 36
news.checked;            // true
form.checkValidity();    // true

localStorage

  • localStorage keeps strings per origin, even after the browser closes
  • sessionStorage works the same but clears when the tab closes
  • Never store secrets, since any script on the page can read them
Language: JavaScript Filename: Save & Load Strings
localStorage.setItem("theme", "dark");
localStorage.getItem("theme");  // "dark"
localStorage.getItem("nope");   // null
localStorage.setItem("count", 1);
localStorage.getItem("count");  // "1"
Language: JavaScript Filename: Store Objects as JSON
const prefs = { theme: "dark", size: 2 };
const json = JSON.stringify(prefs);
localStorage.setItem("prefs", json);
const saved = JSON.parse(
  localStorage.getItem("prefs") ?? "{}",
);
saved.size;              // 2

fetch From the Browser

  • Relative URLs resolve against the page’s address
  • HTTP errors like 404 still resolve, so check response.ok
  • Other origins must allow your page through CORS headers
  • Top-level await needs a module script
Language: JavaScript Filename: Get JSON
const res = await fetch("/api/todos");
if (!res.ok) {
  throw new Error(`HTTP ${res.status}`);
}
const todos = await res.json();
Language: JavaScript Filename: Post JSON
await fetch("/api/todos", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ text: "Ship" }),
});

You can download this information as a printable cheat sheet:

Free Bonus: JavaScript DOM Cheat Sheet

Get the JavaScript DOM Cheat Sheet (PDF), a printable reference to querySelector, addEventListener and event delegation, classList, creating elements, forms and FormData, localStorage, and fetch from the browser:

JavaScript DOM Cheat Sheet