JavaScript 2025 cheatsheet
JavaScript 2025: DOM and browser
10 common JavaScript 2025 tasks.
Find elements
Get the first element that matches a CSS selector, or all matches.
const button = document.querySelector("#save");
const items = document.querySelectorAll(".item");
Listen for events
Run a function when the user clicks.
button.addEventListener("click", (event) => {
console.log("clicked", event.target);
});
Handle events for many elements
Listen once on a parent and check which child was clicked.
list.addEventListener("click", (event) => {
const item = event.target.closest("li");
if (item) select(item);
});
Create and add an element
Build an element and append it to the page.
const li = document.createElement("li");
li.textContent = "New item";
list.append(li);
Set text safely
textContent treats the value as plain text. innerHTML parses HTML.
element.textContent = userInput;
Caution: Setting innerHTML with untrusted input allows cross-site scripting. Use textContent unless you need HTML.
Read a submitted form
Stop the page reload and read the form fields as an object.
form.addEventListener("submit", (event) => {
event.preventDefault();
const data = Object.fromEntries(new FormData(form));
});
Store data in the browser
Save and load JSON in localStorage. It only stores strings.
localStorage.setItem("prefs", JSON.stringify(prefs));
const saved = JSON.parse(localStorage.getItem("prefs") ?? "{}");
Run code when the page is ready
Wait for the HTML to be parsed. Scripts with defer or type=module don't need this.
document.addEventListener("DOMContentLoaded", () => {
init();
});