Selecting Elements

Updated · 6 min read
mediumES2026javascriptdomqueryselectorselectorsinterview

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, or null.
  • document.querySelectorAll(selector) returns a static NodeList of 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").
  • getElementsByClassName and getElementsByTagName return live HTMLCollections that change as the page changes.

querySelector and querySelectorAll

Syntax

syntax.js
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 only

Example

query.html
<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>
Output
Fee Tracker
Tuition
3
Tuition
null
Books, Lab

Explanation: 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

SelectorMatches
#totalThe element with id="total"
.feeElements with the class fee
liAll <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 inputAny <input> inside a <form>, at any depth
h2 + pA <p> right after an <h2>
li:first-child, li:nth-child(2)Position-based matches
input:checked, option:checkedChecked boxes and selected options
li:not(.paid)<li> without the paid class
.card:has(img)Cards that contain an image
a, buttonEither (a list of selectors)
selectors.html
<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>
Output
120
receipt
check
2

Searching 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

MethodReturnsLive?
document.getElementById("id")One element or nulln/a
document.getElementsByClassName("cls")HTMLCollectionLive
document.getElementsByTagName("li")HTMLCollectionLive
document.getElementsByName("amount")NodeListLive

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:

live.html
<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>
Output
2 3

Explanation: 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:

live-bug.html
<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>
Output
2

Removing 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

NodeListHTMLCollection
Returned byquerySelectorAll, childNodesgetElementsBy..., children, form.elements
Live?Static (from querySelectorAll); live from childNodesAlways live
forEachYesNo
for...of, spreadYesYes
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:

unpaid.html
<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>
Output
Unpaid: 2 items, $130
Highlighted: Books

getElementById 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
grade9.html
<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>
Output
Navika, Advitha

Quick check: Selecting elements

3 questions
1What does document.querySelector(".fee") return when three elements have that class?
2Which method returns a live collection?
3How do you use map on the result of querySelectorAll?

Key Takeaways

FindCode
By iddocument.getElementById("total") or querySelector("#total")
First by classquerySelector(".fee")
All by attributequerySelectorAll("[data-grade='9']")
Inside an elementform.querySelector("input")
As an array[...document.querySelectorAll("li")]

Was this tutorial helpful?

Lesson 68 of 139