What is querySelector?

querySelector(selector) returns the first element matching a CSS selector (or null), and querySelectorAll(selector) returns a static NodeList of all matches; both work on document or on any element to search inside it.

Selectors you can use

Anything CSS supports: #id, .class, tag, attributes ([data-id="3"], input[type=email]), combinators (.card > h2, ul li), pseudo-classes (:checked, :not(.hidden), li:nth-child(2n), :has(img)).

Scoping

container.querySelector(".title") searches only inside container, which is faster and avoids matching elements elsewhere on the page.

Static vs live collections

  • querySelectorAll returns a static snapshot: adding elements later does not change it.
  • getElementsByClassName / getElementsByTagName return live HTMLCollections that update automatically, which can surprise you inside loops.

Working with the results

  • NodeList supports forEach and for...of, but not map/filter. Convert with [...nodeList] or Array.from(nodeList).
  • Always handle null from querySelector: document.querySelector("#missing")?.remove().

Related methods

  • element.closest(selector): walks up to the nearest matching ancestor (great for event delegation).
  • element.matches(selector): checks whether an element matches.
  • getElementById is slightly faster for a single id, but the difference rarely matters.

Escaping

For ids or values with special characters, use CSS.escape(value) inside the selector.

Code example

js
1document.body.innerHTML = `
2 <ul id="menu">
3 <li class="item active" data-id="1">Home</li>
4 <li class="item" data-id="2">About</li>
5 <li class="item hidden" data-id="3">Admin</li>
6 </ul>
7 <input type="checkbox" id="agree" checked>`;
8
9const menu = document.querySelector("#menu");
10console.log(menu.querySelector(".active").textContent); // Home
11console.log(document.querySelector('[data-id="2"]').textContent); // About
12console.log(document.querySelector("#missing")); // null
13
14const visible = menu.querySelectorAll(".item:not(.hidden)");
15console.log(visible.length, [...visible].map((li) => li.textContent)); // 2 ["Home", "About"]
16
17console.log(document.querySelector("input:checked")?.id); // agree
18console.log(document.querySelector("ul:has(.hidden)")?.id); // menu
19
20// Static vs live
21const staticList = document.querySelectorAll(".item");
22const liveList = document.getElementsByClassName("item");
23menu.insertAdjacentHTML("beforeend", `<li class="item" data-id="4">Blog</li>`);
24console.log(staticList.length, liveList.length); // 3 4
25
26// closest and matches
27const about = document.querySelector('[data-id="2"]');
28console.log(about.closest("ul").id, about.matches(".item:not(.active)")); // menu true

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app