Lesson 24 / 38

Selecting DOM Elements

Finding elements on the page with CSS selectors.

querySelector

querySelector returns the first match; querySelectorAll returns all matches.

const title = document.querySelector("h1");
const items = document.querySelectorAll(".item");
console.log(title.textContent);
console.log(items.length);

Older selectors

getElementById, getElementsByClassName, getElementsByTagName still work, but querySelector/querySelectorAll accept any CSS selector and are the modern default.

NodeList vs Array

querySelectorAll returns a NodeList, not a real array — use Array.from() or spread [...items] to use array methods on it.