Selecting Elements
Before you can change part of a page, you have to get hold of it. JavaScript gives you methods that search the DOM and hand back element objects. The most useful are querySelector and querySelectorAll, which accept the same selectors you already write in CSS.
A sample page
All the examples on this page use this menu from a small café in Kisumu:
<ul id="menu"> <li class="dish veg">Githeri</li> <li class="dish">Nyama choma</li> <li class="dish veg">Chapati</li> </ul> <p class="note">Prices include VAT.</p>
getElementById
If an element has an id, document.getElementById() is the quickest way to reach it. Pass the id without a #. It returns the element, or null if no element has that id.
const menu = document.getElementById("menu");
console.log(menu.tagName);
console.log(menu.children.length);
querySelector: the first match
document.querySelector(selector) takes any CSS selector and returns the first element that matches, searching from the top of the page. If nothing matches, it returns null.
console.log(document.querySelector(".dish").textContent);
console.log(document.querySelector("#menu li:last-child").textContent);
console.log(document.querySelector("p.note").textContent);
console.log(document.querySelector(".dessert"));
Remember the CSS punctuation: # for an id, . for a class, a space for "inside", and attribute selectors such as [type="email"].
querySelectorAll: every match
querySelectorAll(selector) returns a NodeList holding every match, in page order. If nothing matches you get an empty NodeList (length 0), never null.
const vegDishes = document.querySelectorAll(".dish.veg");
console.log(vegDishes.length);
vegDishes.forEach((li) => console.log(li.textContent));
console.log(vegDishes[1].textContent);
A NodeList has length, index access and forEach, but it is not an array: it has no map or filter. Spread it into a real array first, then use any array method:
const names = [...document.querySelectorAll(".dish")].map((li) => li.textContent);
console.log(names);
Searching inside an element, and searching upwards
You can call querySelector and querySelectorAll on any element, not just document. The search then only looks inside that element, which is faster and avoids picking up matches elsewhere on the page.
const menu = document.getElementById("menu");
const firstVeg = menu.querySelector(".veg");
console.log(firstVeg.textContent);
console.log(firstVeg.matches(".dish")); // does it match this selector?
console.log(firstVeg.closest("ul").id); // nearest ancestor that matches
closest() walks up the tree, starting with the element itself, and returns the nearest match (or null). It becomes very handy for event delegation.
Older methods and live collections
You will also meet getElementsByClassName() and getElementsByTagName() in older code. They return a live HTMLCollection that updates itself when the page changes. A NodeList from querySelectorAll is a static snapshot.
const live = document.getElementsByClassName("dish");
const snapshot = document.querySelectorAll(".dish");
const ugali = document.createElement("li");
ugali.className = "dish";
ugali.textContent = "Ugali";
document.getElementById("menu").append(ugali);
console.log(live.length, snapshot.length);
| Method | Returns | If nothing matches |
|---|---|---|
getElementById("id") | One element | null |
querySelector("css") | First matching element | null |
querySelectorAll("css") | Static NodeList | Empty NodeList |
getElementsByClassName("name") | Live HTMLCollection | Empty collection |
For new code, querySelector and querySelectorAll cover almost everything.
Mixing up the selector styles. getElementById("#menu") returns null because the id is menu, not #menu. And querySelector("menu") looks for a <menu> tag; you need querySelector("#menu"). When a selection returns null, the next line usually crashes with "TypeError: Cannot read properties of null", so check your selector first.
Try it: highlight the vegetarian dishes
Click the button to add a class to every veg dish. Then try changing the selector to .dish:not(.veg) or #menu li:first-child.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight { background: #ffd54f; font-weight: bold; }
</style>
</head>
<body>
<ul id="menu">
<li class="dish veg">Githeri</li>
<li class="dish">Nyama choma</li>
<li class="dish veg">Chapati</li>
</ul>
<button id="show">Highlight veg dishes</button>
<p id="result"></p>
<script>
document.querySelector("#show").addEventListener("click", () => {
const matches = document.querySelectorAll(".dish.veg");
matches.forEach((li) => li.classList.add("highlight"));
document.querySelector("#result").textContent = matches.length + " dishes found";
});
</script>
</body>
</html>
Key points
getElementById("id")finds one element by id (no#).querySelectorreturns the first CSS match ornull;querySelectorAllreturns a NodeList of all matches.- A NodeList has
forEachbut notmap; spread it into an array with[...list]. - Search inside an element with
element.querySelector()and upwards withclosest().
Tip: use the ← and → keys to move between pages.
