JavaScript Interview Question #53

What is the difference between querySelector() and querySelectorAll()?

DOM, Events & Event Loop Fundamentals Mid-Level Intermediate

Quick Interview Answer

querySelector returns only the first element matching a CSS selector. querySelectorAll returns a static NodeList containing all matching elements.

Detailed Explanation

querySelector returns only the first element matching a CSS selector. querySelectorAll returns a static NodeList containing all matching elements.

A NodeList returned by querySelectorAll can be iterated with forEach or for...of. If the DOM later changes, that existing static NodeList does not automatically add newly matching elements.

Code Example

const firstItem = document.querySelector(".item");
const allItems = document.querySelectorAll(".item");

allItems.forEach(item => {
    console.log(item.textContent);
});