Skip to main content
← ⚑ JavaScript & the browserΒ·Module C2 Β· Lesson 2
TaskHTML has three <li class='item'>. Use querySelectorAll to find all .item, then forEach to add the class 'seen' to each. The final DOM should have three <li class='item seen'>.

querySelector + querySelectorAll: CSS selectors in JS

75 XP6 min
Theory

CSS selectors, in code

const first = document.querySelector(".card");        // first .card, or null
const all   = document.querySelectorAll(".card");     // NodeList of every .card

Anything CSS knows, these know. .card, #main, button[type="submit"], ul > li:first-child β€” all valid. That makes selector choice a pure CSS skill.

NodeList β‰  Array

querySelectorAll returns a NodeList, which is array-like but doesn't have .map or .filter directly. Two ways to fix:

all.forEach(el => el.classList.add("seen"));          // forEach works
[...all].map(el => el.textContent);                    // spread β†’ real array

forEach works on NodeList; .map / .filter / .reduce do not. Spread or Array.from() to get an array when you need them.

When getElementById still wins

document.querySelector("#main") and document.getElementById("main") find the same element, but getElementById is ~3Γ— faster because it doesn't parse the selector. For a single id, prefer getElementById. For anything else, querySelector is the right tool.

πŸ”’

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial β€” card required, cancel anytime.

Sign up β€” free trial β†’

First 10 lessons in each track are free. No card needed for those.

← PreviousNext lesson β†’

Get one Python or web tip a day β€” by email

Short, hand-written, no spam. Unsubscribe in one click.