Preskoči na glavni sadržaj
← ⚡ JavaScript & the browser·Modul C2 · Lekcija 2
ZadatakHTML 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 selektori u JS-u

75 XP6 min
Teorija

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.

🔒

Registriraj se i počni kodirati

Teorija je otvorena svima. Editor, pregled uživo i provjera otključavaju se s 7-dnevnim besplatnim probnim periodom — potrebna kartica, otkaži kad god.

Registracija — besplatan probni period →

Prvih 10 lekcija u svakom smjeru je besplatno. Bez kartice.

← PrethodnaSljedeća lekcija →

Jedan Python ili web savjet dnevno — emailom

Kratko, ručno pisano, bez spama. Odjavi se jednim klikom.