After this lesson you will be able to find any element on a page, whether you need one or fifty, and handle the case where it is not there. Selecting is the first step in nearly every DOM task: you cannot change or listen to something you have not found.
querySelector: the all-round tool
querySelector takes a CSS selector, exactly as you would write in a stylesheet, and returns the first element that matches.
document.querySelector("h1"); // first <h1>
document.querySelector("#signup"); // element with id="signup"
document.querySelector(".card"); // first element with class card
document.querySelector("nav a"); // first link inside a nav
document.querySelector("input[type=email]"); // attribute selectorIf you already know CSS selectors, you already know how to use this. If nothing matches, the result is null.
<h1 id="title">Menu</h1>
<p class="note">Open daily.</p>
<p class="note">Closed on Mondays.</p>
<pre id="out"></pre>
<script>
const first = document.querySelector(".note");
const missing = document.querySelector(".nope");
document.getElementById("out").textContent =
"first note: " + first.textContent + "\n" +
"missing: " + missing;
</script>The output shows the text of the first note, and the word null for the missing element. Two notes exist, but querySelector stops at the first.
querySelectorAll: every match
When you want all matches, use querySelectorAll. It returns a NodeList: an ordered, array-like collection. You can loop over it with for...of or forEach, and read its length.
<ul>
<li class="item">Tea</li>
<li class="item">Coffee</li>
<li class="item">Juice</li>
</ul>
<pre id="out"></pre>
<script>
const items = document.querySelectorAll(".item");
let text = "found " + items.length + " items\n";
for (const item of items) {
text += "- " + item.textContent + "\n";
}
document.getElementById("out").textContent = text;
</script>Two details matter. First, the NodeList is a snapshot: if you add another .item later, this list does not grow. Second, a NodeList is not a true array, so it has no map or filter. When you need those, convert it: Array.from(items) or [...items].
const names = Array.from(items).map(item => item.textContent);An empty NodeList is still a list, so a loop over it simply does nothing. It does not give null, which makes it safer than querySelector in that one respect.
getElementById and friends
The older methods still appear in lots of code and are worth recognising:
| Method | Returns |
|---|---|
getElementById("x") |
one element or null; no hash in the argument |
getElementsByClassName("x") |
a live collection |
getElementsByTagName("p") |
a live collection |
"Live" means the collection updates automatically when the page changes, which differs from the snapshot from querySelectorAll. This can cause surprises inside loops that add or remove elements. For new code, many developers use querySelector and querySelectorAll for everything and reach for getElementById when they have an id, simply because it is clear and quick. Both are fine.
Searching inside an element
You can call these methods on any element, not only on document. The search is then limited to that element's descendants. This is useful when a page has repeated blocks.
<section id="a"><h2>Alpha</h2><button>Buy</button></section>
<section id="b"><h2>Beta</h2><button>Buy</button></section>
<pre id="out"></pre>
<script>
const b = document.querySelector("#b");
const heading = b.querySelector("h2");
const buttons = document.querySelectorAll("button").length;
document.getElementById("out").textContent =
"heading inside b: " + heading.textContent + "\n" +
"buttons on the page: " + buttons;
</script>Searching #b finds only "Beta", although the whole page has two headings. This scoping habit keeps code short and avoids picking the wrong element.
Two helpful extras
element.closest(selector)walks up the tree and returns the nearest ancestor (or the element itself) that matches. We use it a lot in the lesson on delegation.element.matches(selector)returnstrueorfalse, telling you whether that element fits a selector.
Choosing good selectors
A selector that is too broad matches the wrong thing, and one that is too fragile breaks when the design changes. Selecting by tag, such as "div", usually matches far more than you meant. Selecting by a long chain such as "main > div > div > p" breaks the moment someone adds a wrapper. A good middle path is to select by a meaningful class or id, and to scope the search to a container you already hold.
Some developers add classes that exist only for JavaScript, with a prefix such as js-, so that restyling the page never breaks the script. Others use data- attributes for the same purpose, for example document.querySelector("[data-role=cart]"). Pick one habit and keep it consistent across your project, so a teammate can tell at a glance which hooks are for styling and which are for code.
Finally, store the result in a variable when you use it more than once. Selecting the same element again and again inside a loop or an event handler is wasted work and harder to read than a single const cart = ... near the top.
Common mistakes
- Forgetting the hash or dot.
querySelector("title")looks for a<title>tag. You meant"#title"or".title". - Adding a hash to getElementById. It expects
"main", not"#main". - Using the result without checking.
document.querySelector(".x").textContentthrows a TypeError if.xdoes not exist. Check withif (el)or use optional chaining,el?.textContent. - Calling
.mapon a NodeList. Convert to an array first. - Expecting querySelectorAll to update. It is a snapshot; run it again after the page changes.
- Using duplicate ids. An id should be unique. With duplicates, only the first one is found.
- Selecting too early. The element must already be in the DOM, as discussed in the previous lesson.
Exercise
Make a page with five <li> elements, two of which have the class done. Write a script that selects all li elements and prints how many there are, then selects only the .done ones and prints their text, joined with commas. Finally print what document.querySelector(".archived") gives, and guard it so the script prints "no archived items" instead of an error.
Key points
- querySelector returns the first element that matches a CSS selector, or null if there is none.
- querySelectorAll returns every match as a static NodeList that you can loop over.
- getElementById is a fast way to find one element by its id; it takes the id without a hash.
- You can call querySelector on an element to search only inside it.
- Always check for null before using the result, and keep selectors specific enough to match what you intend.