querySelector + querySelectorAll: selettori CSS in JS
CSS selectors, in code
const first = document.querySelector(".card"); // first .card, or null
const all = document.querySelectorAll(".card"); // NodeList of every .cardAnything 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 arrayforEach 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.
Iscriviti per iniziare a programmare
La teoria è aperta a tutti. Editor, anteprima e check si sbloccano con una prova gratuita di 7 giorni — carta richiesta, annullabile in qualsiasi momento.
Iscriviti — prova gratuita →Le prime 10 lezioni di ogni percorso sono gratuite. Nessuna carta richiesta.