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
querySelectorAllreturns a static snapshot: adding elements later does not change it.getElementsByClassName/getElementsByTagNamereturn liveHTMLCollections that update automatically, which can surprise you inside loops.
Working with the results
NodeListsupportsforEachandfor...of, but notmap/filter. Convert with[...nodeList]orArray.from(nodeList).- Always handle
nullfromquerySelector: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.getElementByIdis 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
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>`;89const menu = document.querySelector("#menu");10console.log(menu.querySelector(".active").textContent); // Home11console.log(document.querySelector('[data-id="2"]').textContent); // About12console.log(document.querySelector("#missing")); // null1314const visible = menu.querySelectorAll(".item:not(.hidden)");15console.log(visible.length, [...visible].map((li) => li.textContent)); // 2 ["Home", "About"]1617console.log(document.querySelector("input:checked")?.id); // agree18console.log(document.querySelector("ul:has(.hidden)")?.id); // menu1920// Static vs live21const 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 42526// closest and matches27const 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.