Quiz Entry - updated: 2026.07.05
What does document.querySelector return if no element matches?
querySelector returns null when nothing matches, so guard the result before using it (querySelectorAll instead returns an empty NodeList).
const element = document.querySelector(".nonexistent");
// null
console.log(element);
// DANGER - this will throw an error!
// TypeError: Cannot read property 'classList' of null
element.classList.add("active");
Always check before using:
const element = document.querySelector(".maybe-exists");
if (element) {
element.classList.add("active");
}
// Or with optional chaining (modern JS)
element?.classList.add("active");
Note: querySelectorAll returns an empty NodeList (not null) if nothing matches:
const elements = document.querySelectorAll(".nonexistent");
// 0
console.log(elements.length);
Go deeper:
document.querySelector (MDN) — first match by CSS selector, returns
nullwhen nothing matches.