Selecting Elements
Selecting elements means finding the DOM nodes you want to read or change. The modern methods, querySelector and querySelectorAll, accept any CSS selector, the same patterns you use in stylesheets, so one skill covers both. The older methods (getElementById, getElementsByClassName, getElementsByTagName) still work and are worth recognizing, especially because some return live collections that update by themselves.
In One Minute
document.querySelector(selector)returns the first matching element, ornull.document.querySelectorAll(selector)returns a staticNodeListof every match (possibly empty).- Any CSS selector works:
#id,.class,tag,[attribute],parent > child,:checked... - Call them on an element to search only inside it:
form.querySelector("input"). getElementsByClassNameandgetElementsByTagNamereturn liveHTMLCollections that change as the page changes.
querySelector and querySelectorAll
Syntax
const first = document.querySelector("css selector"); // Element or null
const all = document.querySelectorAll("css selector"); // NodeList (static)
const inside = someElement.querySelector("css selector"); // search within someElement onlyExample
<h1 id="title">Fee Tracker</h1>
<ul class="fees">
<li class="fee paid">Tuition</li>
<li class="fee">Books</li>
<li class="fee">Lab</li>
</ul>
<script>
console.log(document.querySelector("#title").textContent);
console.log(document.querySelector(".fee").textContent);
console.log(document.querySelectorAll(".fee").length);
console.log(document.querySelector(".fee.paid").textContent);
console.log(document.querySelector(".missing"));
const names = [...document.querySelectorAll(".fees li:not(.paid)")].map((li) => li.textContent);
console.log(names.join(", "));
</script>Fee Tracker
Tuition
3
Tuition
null
Books, LabExplanation: querySelector(".fee") returns only the first match. querySelectorAll returns all of them as a NodeList, which you can loop with for...of or spread into an array to use map and filter. A selector that matches nothing gives null (from querySelector) or an empty list (from querySelectorAll).
Selectors That Work in JavaScript
| Selector | Matches |
|---|---|
#total | The element with id="total" |
.fee | Elements with the class fee |
li | All <li> elements |
li.fee.paid | <li> elements with both classes |
[data-grade] | Elements with a data-grade attribute |
[data-grade="9"] | ...with that exact value |
input[type="email"] | Email inputs |
ul > li | <li> that are direct children of a <ul> |
form input | Any <input> inside a <form>, at any depth |
h2 + p | A <p> right after an <h2> |
li:first-child, li:nth-child(2) | Position-based matches |
input:checked, option:checked | Checked boxes and selected options |
li:not(.paid) | <li> without the paid class |
.card:has(img) | Cards that contain an image |
a, button | Either (a list of selectors) |
<form id="payment">
<input name="amount" type="number" value="120">
<label><input type="checkbox" name="receipt" checked> Email receipt</label>
<select name="method">
<option value="card">Card</option>
<option value="check" selected>Check</option>
</select>
</form>
<script>
const form = document.querySelector("#payment");
console.log(form.querySelector('[name="amount"]').value);
console.log(form.querySelector("input:checked").name);
console.log(form.querySelector("option:checked").value);
console.log(form.querySelectorAll("input").length);
</script>120
receipt
check
2Searching from form instead of document keeps the search inside that form, which is faster and avoids matching a field with the same name elsewhere on the page.
Older Methods
| Method | Returns | Live? |
|---|---|---|
document.getElementById("id") | One element or null | n/a |
document.getElementsByClassName("cls") | HTMLCollection | Live |
document.getElementsByTagName("li") | HTMLCollection | Live |
document.getElementsByName("amount") | NodeList | Live |
getElementById is still common and slightly faster than querySelector("#id"); note that it takes the id without #. The others return live collections, explained next.
Live vs Static Collections
A static collection is a snapshot taken when you call the method. A live collection is a view that updates automatically whenever the DOM changes:
<ul id="list">
<li class="fee">Tuition</li>
<li class="fee">Books</li>
</ul>
<script>
const staticList = document.querySelectorAll(".fee");
const liveList = document.getElementsByClassName("fee");
const li = document.createElement("li");
li.className = "fee";
li.textContent = "Lab";
document.querySelector("#list").append(li);
console.log(staticList.length, liveList.length);
</script>2 3Explanation: after a new .fee item was added, the static NodeList from querySelectorAll still has 2 items, while the live HTMLCollection from getElementsByClassName has 3.
Live collections cause a classic bug: removing items while looping over a live collection skips every other item, because the collection shrinks under the loop:
<p class="note">A</p><p class="note">B</p><p class="note">C</p><p class="note">D</p>
<script>
const notes = document.getElementsByClassName("note");
for (let i = 0; i < notes.length; i++) {
notes[i].classList.remove("note");
}
console.log(document.getElementsByClassName("note").length);
</script>2Removing the class from the first item removes it from the live collection, so the second item moves to index 0, and the loop's i = 1 skips it. With querySelectorAll (a static snapshot), all four would be processed.
NodeList vs HTMLCollection
NodeList | HTMLCollection | |
|---|---|---|
| Returned by | querySelectorAll, childNodes | getElementsBy..., children, form.elements |
| Live? | Static (from querySelectorAll); live from childNodes | Always live |
forEach | Yes | No |
for...of, spread | Yes | Yes |
Array methods (map, filter) | No (spread first) | No (spread first) |
Neither is a real array. [...list] or Array.from(list) converts either one.
In Practice
The Fee Tracker selects unpaid items by a data- attribute, totals them, and highlights the most expensive one, searching only inside the fee table:
<table id="fees">
<tr data-status="paid"><td>Tuition</td><td data-amount="400">$400</td></tr>
<tr data-status="unpaid"><td>Books</td><td data-amount="85">$85</td></tr>
<tr data-status="unpaid"><td>Lab</td><td data-amount="45">$45</td></tr>
</table>
<script>
const table = document.getElementById("fees");
const unpaidRows = [...table.querySelectorAll('tr[data-status="unpaid"]')];
const amountOf = (row) => Number(row.querySelector("[data-amount]").dataset.amount);
const total = unpaidRows.reduce((sum, row) => sum + amountOf(row), 0);
const biggest = unpaidRows.reduce((a, b) => (amountOf(b) > amountOf(a) ? b : a));
biggest.classList.add("highlight");
console.log(`Unpaid: ${unpaidRows.length} items, $${total}`);
console.log(`Highlighted: ${biggest.cells[0].textContent}`);
</script>Unpaid: 2 items, $130
Highlighted: BooksgetElementById finds the table, a data- attribute selector picks the unpaid rows, and every later search (row.querySelector) stays inside one row. row.cells is a table-row property listing its cells.
Common Mistakes
Forgetting # or . in querySelector. querySelector("total") looks for a <total> tag. Use "#total".
Adding # to getElementById. getElementById("#total") looks for an id that literally starts with #.
Using the result without checking for null. querySelector(".missing").textContent throws TypeError. Check, or use ?..
Calling array methods on a NodeList. list.map is undefined. Spread it: [...list].map(...).
Interview Corner
What is the difference between querySelectorAll and getElementsByClassName?
querySelectorAll takes any CSS selector and returns a static NodeList snapshot. getElementsByClassName takes class names only and returns a live HTMLCollection that updates as the DOM changes, which can cause bugs when modifying elements in a loop. querySelectorAll results support forEach; HTMLCollections don't.
What does querySelector return when nothing matches?
null, while querySelectorAll returns an empty NodeList. Code that immediately reads a property of the result should check for null or use optional chaining.
Practice
Challenge: Select every <li> with data-grade="9" inside #students and log their names, joined by commas.
Show solution
<ul id="students">
<li data-grade="9">Navika</li>
<li data-grade="11">Srihitha</li>
<li data-grade="9">Advitha</li>
</ul>
<script>
const names = [...document.querySelectorAll('#students li[data-grade="9"]')].map((li) => li.textContent);
console.log(names.join(", "));
</script>Navika, AdvithaKey Takeaways
| Find | Code |
|---|---|
| By id | document.getElementById("total") or querySelector("#total") |
| First by class | querySelector(".fee") |
| All by attribute | querySelectorAll("[data-grade='9']") |
| Inside an element | form.querySelector("input") |
| As an array | [...document.querySelectorAll("li")] |
Was this tutorial helpful?