How to select DOM elements with querySelector and querySelectorAll

· Category: JavaScript

Short answer

querySelector returns the first matching element, while querySelectorAll returns a static NodeList of all matches. Both accept any valid CSS selector string.

Steps

  1. Select a single element: javascript const header = document.querySelector("#main-header");
  2. Select multiple elements: javascript const items = document.querySelectorAll(".list-item"); items.forEach(el => el.classList.add("active"));
  3. Use complex CSS selectors: javascript const btn = document.querySelector('nav button[data-action="save"]');
  4. Scope queries within a parent element: javascript const card = document.querySelector(".card"); const title = card.querySelector(".title");

Tips

  • Prefer querySelector over getElementById for consistency, though the latter is slightly faster.
  • querySelectorAll returns a NodeList, not an Array; use Array.from() or the spread operator if you need array methods like map.

Common issues

  • Forgetting that querySelectorAll is static; it does not update automatically when the DOM changes.
  • Using overly broad selectors that match unexpected elements and hurt performance.