The DOM is the browser’s model of your page — every element as an object you can read and change from JavaScript. Almost all browser JavaScript is three operations: find something, change it, or respond to something happening to it. This guide covers all three, plus the two patterns that separate code that works from code that stays fast.
Finding elements#
const title = document.querySelector("h1");
const button = document.querySelector("#save");
const first = document.querySelector(".item");
const items = document.querySelectorAll(".item"); // all matches
// Within another element, not the whole document
const price = card.querySelector(".price");
querySelector takes any CSS selector, which makes it the only one you really need. The older methods still exist and have one important difference:
document.getElementsByClassName("item"); // live - updates automatically
document.querySelectorAll(".item"); // static - a snapshot
A live collection changing underneath a loop is a classic source of skipped elements. The static list from querySelectorAll is more predictable, and it is a real array-like you can spread:
[...document.querySelectorAll(".item")].filter(el => el.dataset.active === "true");
Changing content#
element.textContent = "New text"; // safe, inserts text
element.innerHTML = "<b>markup</b>"; // parses HTML - dangerous with user data
Use textContent unless you specifically need to insert markup you generated yourself. Setting innerHTML to anything a visitor supplied is how cross-site scripting happens.
// Attributes
link.href = "/about";
img.src = "/photo.jpg";
input.value = "Ana";
button.disabled = true;
element.setAttribute("aria-expanded", "true");
element.getAttribute("data-id");
element.removeAttribute("hidden");
// Data attributes
element.dataset.productId = "42"; // becomes data-product-id
console.log(element.dataset.productId);
Classes and styles#
element.classList.add("active");
element.classList.remove("hidden");
element.classList.toggle("open");
element.classList.toggle("open", shouldBeOpen); // force a state
element.classList.contains("active");
// Direct styles - fine for dynamic values
element.style.width = progress + "%";
element.style.setProperty("--accent", "#2563eb");
Creating elements#
const li = document.createElement("li");
li.className = "item";
li.textContent = product.name;
li.dataset.id = product.id;
list.append(li);
The modern insertion methods are more readable than the old ones:
parent.append(child); // at the end, accepts several, accepts text
parent.prepend(child); // at the start
element.before(node); // as a sibling
element.after(node);
element.replaceWith(node);
element.remove(); // removes itself
element.insertAdjacentHTML("beforeend", "<li>Item</li>");
Building many elements one at a time causes a layout recalculation per insertion. Build them off-screen and insert once:
const fragment = document.createDocumentFragment();
for (const product of products) {
const li = document.createElement("li");
li.textContent = product.name;
fragment.append(li);
}
list.append(fragment); // one insertion, one reflow
Templates#
<template id="card-template">
<article class="card">
<h3 class="card__title"></h3>
<p class="card__price"></p>
</article>
</template>
const template = document.querySelector("#card-template");
function makeCard(product) {
const card = template.content.cloneNode(true);
card.querySelector(".card__title").textContent = product.name;
card.querySelector(".card__price").textContent = "£" + product.price.toFixed(2);
return card;
}
products.forEach(p => list.append(makeCard(p)));
The markup lives in the HTML where it is easy to read and edit, and the values go in through textContent, so escaping is automatic. This is the pattern to reach for instead of building HTML strings.
Events#
button.addEventListener("click", (event) => {
console.log("clicked", event.target);
});
form.addEventListener("submit", (event) => {
event.preventDefault(); // stop the page reloading
const data = Object.fromEntries(new FormData(form));
console.log(data);
});
input.addEventListener("input", (event) => {
console.log(event.target.value);
});
Removing a listener requires a reference to the same function, which an inline arrow does not give you:
function onClick() { }
button.addEventListener("click", onClick);
button.removeEventListener("click", onClick);
// Or let the browser clean up
button.addEventListener("click", onClick, { once: true });
const controller = new AbortController();
button.addEventListener("click", onClick, { signal: controller.signal });
controller.abort(); // removes every listener using this signal
Event delegation#
The pattern worth learning properly. Instead of a listener per item, put one on the container:
// Breaks for items added later
document.querySelectorAll(".delete").forEach(btn =>
btn.addEventListener("click", handleDelete));
// Works for items added at any time
list.addEventListener("click", (event) => {
const button = event.target.closest(".delete");
if (!button || !list.contains(button)) return;
const id = button.closest("li").dataset.id;
handleDelete(id);
});
Events bubble up from the element to its ancestors, so the container hears clicks on everything inside it. closest() walks up from whatever was actually clicked — which might be an icon inside the button — to find the element you care about.
One listener instead of a thousand, and it keeps working when rows are added or removed.
Reading position and size#
const box = element.getBoundingClientRect();
console.log(box.top, box.left, box.width, box.height);
console.log(window.scrollY);
element.scrollIntoView({ behavior: "smooth", block: "center" });
// Reacting to an element entering the viewport
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) entry.target.classList.add("visible");
});
}, { threshold: 0.2 });
document.querySelectorAll(".fade-in").forEach(el => observer.observe(el));
An IntersectionObserver is far cheaper than a scroll listener calling getBoundingClientRect on every frame — use it for lazy loading and scroll animations.
Layout thrashing#
// Slow - forces a layout recalculation on every iteration
for (const el of elements) {
el.style.height = el.offsetHeight + 10 + "px";
}
// Fast - read everything, then write everything
const heights = elements.map(el => el.offsetHeight);
elements.forEach((el, i) => {
el.style.height = heights[i] + 10 + "px";
});
Reading a layout property such as offsetHeight after writing a style forces the browser to recalculate immediately. Alternating reads and writes in a loop makes it recalculate every time, which is the single most common cause of janky JavaScript.
Watching for changes#
const observer = new MutationObserver((mutations) => {
mutations.forEach(m => console.log(m.type, m.target));
});
observer.observe(container, { childList: true, subtree: true });
Useful when content is inserted by code you do not control. Use it sparingly — it fires a great deal on a busy page.
Questions people ask#
Why is my element null?
Either the script ran before the element existed, or the selector does not match. Print the selector result immediately after querying it; if it is null, check the script’s position in the page first.
innerHTML or textContent?
textContent by default. It is faster, and it cannot execute markup. Use innerHTML only for HTML you generated, and sanitise anything that came from a user.
What is the difference between target and currentTarget?
target is what was actually clicked; currentTarget is the element the listener is attached to. In event delegation you want target, usually via closest().
Do I need to remove event listeners?
Not for elements removed from the page — those are collected along with their listeners. Do remove listeners attached to window or document from a component that goes away, or they keep firing forever.
Where to go next#
- JavaScript basics — the language underneath.
- Arrays and objects in JavaScript — the data you render.
- JavaScript security — why innerHTML matters.