Quiz Entry - updated: 2026.06.20
How do you select elements using CSS selector syntax in JavaScript?
Use querySelector() for the first match or querySelectorAll() for all matches, both taking CSS selector syntax.
// Single element (first match)
const first = document.querySelector(".card");
const byId = document.querySelector("#main");
const nested = document.querySelector("nav > ul > li");
// All matching elements
const allCards = document.querySelectorAll(".card");
const allLinks = document.querySelectorAll("a[href^='https']");
Key points:
- Uses CSS selector syntax (same as stylesheets)
querySelectorreturns first match ornullquerySelectorAllreturns static NodeList (can be empty)- Can use complex selectors:
"div.container > p:first-child"
Iterating results:
document.querySelectorAll(".item").forEach(item => {
console.log(item.textContent);
});