Skip to content
Kuza Ndoto Academy

Selecting Elements

Beginner → IntermediateChapter 4 · Page 18 of 324 min readUpdated 15 Nov 2026

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);
UL 3

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"));
Githeri Chapati Prices include VAT. null

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);
2 Githeri Chapati Chapati

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);
['Githeri', 'Nyama choma', 'Chapati']
getElementById("menu") querySelector(".dish") querySelectorAll(".dish.veg") ul#menuul#menuul#menu Githeri (veg) Nyama choma Chapati (veg) Githeri (veg) Nyama choma Chapati (veg) Githeri (veg) Nyama choma Chapati (veg) p.note p.note p.note one element (by id) first match only NodeList of 2 elements
Figure 1. The same page, three methods. Highlighted boxes are what each call returns.

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
Githeri true menu

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);
4 3
MethodReturnsIf nothing matches
getElementById("id")One elementnull
querySelector("css")First matching elementnull
querySelectorAll("css")Static NodeListEmpty NodeList
getElementsByClassName("name")Live HTMLCollectionEmpty collection

For new code, querySelector and querySelectorAll cover almost everything.

Common mistake

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 #).
  • querySelector returns the first CSS match or null; querySelectorAll returns a NodeList of all matches.
  • A NodeList has forEach but not map; spread it into an array with [...list].
  • Search inside an element with element.querySelector() and upwards with closest().
Up next · The DOM & EventsChanging Content & StylestextContent, innerHTML, classList and creating elements.
→

Tip: use the ← and → keys to move between pages.