Explain it simply
Explain it simply
Before you can change an element in the DOM tree, you have to find it. Selector methods work like finding a person: getElementById is like looking someone up by their ID number, one exact person. querySelector searches by description instead, like "the first person wearing a blue shirt", written as a CSS selector.
querySelectorAll returns a list of everyone matching the description. When nothing matches, querySelector returns null while querySelectorAll returns an empty list, and that difference is behind a lot of bugs.
Problem → Why → Solution
The problem: tiny selector slips, confusing errors
All three lines below look right, and none of them works. The first two quietly return null with no error, and the crash only comes on a later line as "Cannot read properties of null". The third throws "map is not a function" because it assumes querySelectorAll returns an array.
// HTML: <div id="menu"><li class="dish">Mohinga</li>...</div>
const menu = document.getElementById("#menu"); // null: no # in getElementById
const first = document.querySelector("dish"); // null: looks for a <dish> tag
const names = document.querySelectorAll(".dish")
.map((li) => li.textContent); // TypeError: map is not a function
console.log(first.textContent); // TypeError: Cannot read properties of nullWhat went wrong?
getElementById takes a bare id string, so "#menu" searches for an element whose id is literally "#menu". querySelector takes a CSS selector, so a class needs its dot: "dish" means a <dish> tag. querySelectorAll returns a NodeList, not an array; it has forEach but no map. Knowing what each method accepts and returns prevents all three mistakes.
Core concept: what each method takes and returns
Every DOM change in the coming lessons starts with a lookup like these, so a wrong lookup is behind many "my code does nothing" reports. Choose a method by asking two questions: do I want one element or many, and do I need a live list that follows DOM changes?
| Method | Returns | When nothing matches |
|---|---|---|
| getElementById("menu") | One element | null |
| querySelector("#menu .dish") | The first matching element | null |
| querySelectorAll(".dish") | A static NodeList | An empty NodeList (length 0) |
| getElementsByClassName("dish") | A live HTMLCollection | An empty collection |
getElementById takes a plain id string and returns a single element, since ids must be unique within a page. querySelector and querySelectorAll accept the same CSS selectors you write in a stylesheet: #id, .class, a tag name, attribute selectors such as [data-id="3"], descendant selectors such as "#menu li", and compound ones such as ".dish.veg" that require both classes. querySelector returns the first match in document order.
These methods work on any element, not just on document. menu.querySelectorAll("li") searches only inside menu, so li elements elsewhere on the page are left out, which is both faster and more precise. (getElementById is the exception: it exists only on document.)
data-* attributes are written as [data-id="3"] in a selector and read in JavaScript through element.dataset. A dashed attribute name such as data-stock-level becomes camelCase in dataset: dataset.stockLevel. Every value that comes out of dataset is a string, so convert it with Number() before doing arithmetic.
The NodeList from querySelectorAll looks like an array but is not one. It has length, indexes and forEach, but no map, filter or reduce, so convert it first with [...list] or Array.from(list). Keeping an element in a variable saves searching for it again, but beware: if that node is later replaced, for example through innerHTML, your saved reference still points at the old node, which is no longer on the page.
- Write the selector the CSS way
- Search from a parent to narrow scope
- Check for null or length 0
- Spread lists into arrays, then use
Single-element methods can return null; multi-element methods return an empty list; none of them returns undefined.
General pattern
const one = document.getElementById("id-without-hash"); // element | null
const first = root.querySelector("css selector"); // element | null
const all = root.querySelectorAll("css selector"); // static NodeList
if (first === null) {
// handle the missing element
}
const values = [...all].map((element) => element.dataset.someKey);root can be document or any element that narrows the search. Always check single-element results for null, and spread multi-element results into an array. A data-some-key attribute is read as dataset.someKey (camelCase).
Example: searching inside a menu
This code builds the menu HTML it searches, so it runs directly in the console of a blank page. It uses each selector method once, and the last line shows what you get when you search for an element that does not exist.
// Build the HTML we will search (paste into the console of a blank page).
const app = document.createElement("div");
app.id = "menu";
app.innerHTML = `
<h2 class="title">Today's menu</h2>
<ul>
<li class="dish" data-id="1">Mohinga</li>
<li class="dish veg" data-id="2">Tea leaf salad</li>
<li class="dish" data-id="3">Shan noodles</li>
</ul>`;
document.body.append(app);
const menu = document.getElementById("menu");
const firstDish = document.querySelector("#menu .dish");
const vegDishes = document.querySelectorAll("#menu .dish.veg");
const allDishes = menu.querySelectorAll("li");
const noodles = menu.querySelector('[data-id="3"]');
console.log(menu.id);
console.log(firstDish.textContent);
console.log(vegDishes.length, vegDishes[0].textContent);
console.log([...allDishes].map((li) => li.dataset.id).join(","));
console.log(noodles.textContent);
console.log(document.querySelector("#missing"));Code breakdown
- By id
const menu = document.getElementById("menu");Just the id text, no #. Because ids are unique, exactly one element comes back.
- First match
const firstDish = document.querySelector("#menu .dish");Reads as "an element with class dish inside #menu". Three elements match, but only the first, Mohinga, is returned.
- Compound class selector
const vegDishes = document.querySelectorAll("#menu .dish.veg");.dish.veg with no space means one element carrying both classes, so only Tea leaf salad matches. ".dish .veg" with a space would look for a .veg inside a .dish and find nothing.
- NodeList to array
console.log([...allDishes].map((li) => li.dataset.id).join(","));A NodeList has no map, so it is spread into an array first. dataset.id reads the data-id attribute as a string.
- Attribute selector
const noodles = menu.querySelector('[data-id="3"]');Called on menu, so it only searches inside menu, and it picks the element whose data-id is "3".
- No match
console.log(document.querySelector("#missing"));Nothing matches, so the result is null; calling .textContent on it would throw a TypeError.
menu
Mohinga
1 Tea leaf salad
1,2,3
Shan noodles
nullLive HTMLCollection versus static NodeList
getElementsByClassName and getElementsByTagName return a live HTMLCollection that updates itself whenever the DOM changes. querySelectorAll returns a snapshot taken at call time (a static NodeList) that does not change when elements are added later. Removing elements while looping over a live collection shifts the indexes and silently skips items, so be careful.
const list = document.createElement("ul");
list.innerHTML = "<li class='item'>A</li><li class='item'>B</li>";
document.body.append(list);
const live = list.getElementsByClassName("item"); // HTMLCollection (live)
const snapshot = list.querySelectorAll(".item"); // NodeList (static)
const extra = document.createElement("li");
extra.className = "item";
extra.textContent = "C";
list.append(extra);
console.log(live.length); // 3: updates by itself
console.log(snapshot.length); // 2: still the old snapshotSearching upward: closest() and matches()
querySelector searches downward through an element's descendants. Sometimes you need the opposite, such as finding the list item that owns a button. element.closest("li") starts at the element itself, climbs through its ancestors and returns the first match, or null. element.matches(".veg") simply answers true or false for whether one element fits a selector. Both become key tools for event delegation in the DOM Events lesson.
In real projects
Where this shows up in real projects
In a todo app, the form, input and list elements are usually looked up once when the script starts and kept in variables. The app cannot work without them, so a helper like requireElement() that fails immediately with "Missing element: #todo-form" saves far more time than chasing null errors later.
Designers rename styling classes often. If JavaScript behaviour is tied to a presentation class such as .btn-red, a CSS refactor can quietly break a feature. That is why many teams use data-* attributes such as data-action="delete" or data-id="42" as JavaScript hooks. Test tools like Playwright and Testing Library likewise recommend locating elements by role or by a stable attribute such as data-testid rather than by class names.
Common mistakes
Common mistakes
1. Adding # to getElementById or dropping the dot in querySelector
getElementById("#menu") and querySelector("dish") both return null without any error. Give getElementById the bare id, and write #id and .class in querySelector exactly as in CSS.
2. Using the result without checking for null
An element that exists on only some pages is null on the others, and the whole script stops. Throw a clear error when the element is required, or guard with if (el) or el?.remove() when it is optional.
3. Treating a NodeList like an array
querySelectorAll(...).map() throws "map is not a function". forEach works directly, but for map, filter and reduce convert first with [...list] or Array.from(list).
Best practices
Best practices
- Default to querySelector for one element and querySelectorAll for many; one selector style throughout is easier to read.
- Look up important elements once when the script starts and keep them in well-named const variables.
- Avoid long structural selectors such as body > div > div > ul, which break whenever the HTML shifts slightly.
Mini challenge
Mini challenge: the shop's in-stock items
Build a product list, select the in-stock items through data-* attributes, and print their names and total price. Also write a helper that gives a clear error when a required element is missing.
- Build a <ul class="products"> with Pen (3, in), Lamp (12, out) and Mug (7, in) using data-price and data-stock
- requireElement(selector, root) throws "Missing element: ..." when nothing matches
- Select in-stock items with a [data-stock="in"] selector and turn them into an array
- Convert dataset.price with Number() before adding
// TODO: build a <section> holding <ul class="products"> with three <li> items
// (data-price and data-stock attributes) and append it to document.body
function requireElement(selector, root = document) {
// TODO: querySelector inside root; throw an Error naming the selector if null
}
// TODO: find .products, then its [data-stock="in"] items as an array
// TODO: print "In stock: ..." and "Total price: ..."
// TODO: show the error message for requireElement(".cart", section)Expected: The console shows: In stock: Pen, Mug Total price: 10 Missing element: .cart
Show hint
dataset gives you strings, so "3" + "7" would be "37"; convert with Number() before adding. Wrap the querySelectorAll result in [...] to get map and reduce.
Show solution
// Builds its own elements, so it works on any blank page.
const shop = document.createElement("section");
shop.innerHTML =
'<ul class="products">' +
'<li data-price="3" data-stock="in">Pen</li>' +
'<li data-price="12" data-stock="out">Lamp</li>' +
'<li data-price="7" data-stock="in">Mug</li>' +
"</ul>";
document.body.append(shop);
function requireElement(selector, root = document) {
const element = root.querySelector(selector);
if (element === null) {
throw new Error(`Missing element: ${selector}`);
}
return element;
}
const list = requireElement(".products", shop);
const inStock = [...list.querySelectorAll('[data-stock="in"]')];
const names = inStock.map((li) => li.textContent);
const total = inStock.reduce((sum, li) => sum + Number(li.dataset.price), 0);
console.log(`In stock: ${names.join(", ")}`);
console.log(`Total price: ${total}`);
try {
requireElement(".cart", shop);
} catch (error) {
console.log(error.message);
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- getElementById takes an id without #, while querySelector and querySelectorAll accept any CSS selector.
- Single-element methods can return null, so check; multi-element methods return an empty list instead.
- querySelectorAll gives a static NodeList and getElementsBy... a live HTMLCollection; spread into an array to use map.
- Narrow searches with element.querySelector() and use data-* attributes as JavaScript hooks.
MDN — Document Object Model (DOM) — MDN Web Docs