return elements that match specified CSS selector(s)

Using querySelectorAll() in JavaScript

The document.querySelectorAll() method returns a static (not live) NodeList of all elements matching a given CSS selector string[1]. You can pass any valid CSS selector (tag, class, ID, attribute, or combination).

Example Selection

For example, to select all <p> tags on the page:

const paragraphs = document.querySelectorAll("p");

This returns a NodeList of all <p> elements[2]. The string of selectors must be valid CSS; otherwise a SyntaxError is thrown[3].

Selector Types

  • Tag name: Use the tag name directly. E.g.
    const items = document.querySelectorAll("li");
  • Class: Prefix the class name with .. E.g.
    const activeItems = document.querySelectorAll(".active");
  • ID: Prefix the ID with #. Although IDs are unique, querySelectorAll("#myId") still returns a NodeList (of length 0 or 1). E.g.
    const header = document.querySelectorAll("#main-header");
  • Attribute: Use [attr="value"] syntax. E.g.
    const checkedBoxes = document.querySelectorAll('input[type="checkbox"]');
    const highlighted = document.querySelectorAll("[data-highlight]");

    MDN gives an example selecting by attribute which finds all <iframe> elements that have a data-src attribute[4]:

    const iframes = document.querySelectorAll("iframe[data-src]");

Combinations

You can combine selectors or use descendant/child selectors like in CSS.

  • Elements with two classes:
    const special = document.querySelectorAll(".item.active");
  • Direct children selector (only <li> directly inside <ul> with class "menu"):
    const menuItems = document.querySelectorAll("ul.menu > li");
  • Multiple selectors (all .note and all .alert divs):
    const notesAndAlerts = document.querySelectorAll("div.note, div.alert");

    The MDN docs show combining selectors: document.querySelectorAll("div.note, div.alert") returns all <div> elements with class note or alert[5].

  • Complex nesting example:
    const container = document.querySelector("#test");
    const highlightedParagraphs = container.querySelectorAll("div.highlighted > p");

    This finds <p> elements whose parent is a <div class="highlighted"> inside the element with id="test"[6].


Iterating Through the Results

The NodeList returned by querySelectorAll() can be treated like an array (it has a .length, indices, and in modern browsers it supports .forEach()).

Example: Changing Styles
const buttons = document.querySelectorAll(".btn");
buttons.forEach(btn => {
  btn.style.color = "blue";
});

This uses forEach to loop over all matched elements[7].

If you need to support very old browsers that lack forEach on NodeList, you can use a traditional for loop or convert to an array (e.g. Array.from(nodeList)) and then use array methods.


querySelectorAll() vs. Older DOM Methods

Method Return Type Live/Static Selector Support
querySelectorAll() NodeList Static (snapshot) [1] Full CSS Selector (tag, class, ID, attribute, etc.) [3]
getElementsByClassName() HTMLCollection Live (updates with DOM) [8] Only Class Name
getElementsByTagName() HTMLCollection Live (updates with DOM) [9] Only Tag Name

The specialized older methods can be faster for their specific use-cases, but querySelectorAll() is more flexible and widely supported (even IE8+)[10].


Practical Examples

You can use classList on elements found by querySelectorAll(). For instance, to add an "active" class to a clicked button and remove it from others:

HTML Structure:

<div class="nav">
  <button class="btn">A</button>
  <button class="btn active">B</button>
  <button class="btn">C</button>
</div>

JavaScript:

<script>
  const btns = document.querySelectorAll('.btn');
  btns.forEach(btn => {
    btn.addEventListener('click', function() {
      // remove 'active' from all
      btns.forEach(b => b.classList.remove('active'));
      // add 'active' to the clicked one
      this.classList.add('active');
    });
  });
</script>

This pattern uses forEach to loop over all buttons, attaching a click handler. The clicked button becomes highlighted while others are reset[11].

You can easily update CSS styles on all selected elements. E.g., turning all paragraphs red:

const paragraphs = document.querySelectorAll("p");
paragraphs.forEach(p => {
  p.style.color = "red";
});

Or to hide all images with a certain class:

const images = document.querySelectorAll("img.thumbnail");
images.forEach(img => {
  img.style.display = "none";
});

You can select elements with data- attributes and read their values via the .dataset property. Suppose you have:

<article data-index-number="12314" data-parent="cars">...</article>
<article data-index-number="12315" data-parent="cars">...</article>

JavaScript could select and read them:

// Select all articles with data-index-number="12314"
const specialArticles = document.querySelectorAll('article[data-index-number="12314"]');
specialArticles.forEach(article => {
  console.log(article.dataset.parent); // "cars"
});

MDN shows selecting by [data-columns="3"] and then reading article.dataset.indexNumber[12].

Since querySelectorAll() returns multiple elements, you must loop and attach listeners to each one.

HTML Structure:

<button class="notify">Hello</button>
<button class="notify">World</button>

JavaScript:

<script>
  const buttons = document.querySelectorAll('.notify');
  buttons.forEach(btn => {
    btn.addEventListener('click', () => {
      alert('Button clicked!');
    });
  });
</script>

You cannot call addEventListener on a NodeList directly – you must loop through the list[13]. Another example toggles a class on click[14]:

let cbox = document.querySelectorAll(".box");
cbox.forEach(box => {
  box.addEventListener('click', () => box.classList.toggle("red"));
});

Using querySelectorAll() with React

In React, direct DOM manipulation is generally discouraged[15]. React prefers you update the UI by changing state and letting React manage the DOM.

Directly using document.querySelectorAll() breaks the “React way” of declarative UI. Most React tutorials advise using refs or React state instead of manual DOM queries[15].

If absolutely necessary (e.g. integrating a third-party library), use querySelectorAll() inside a useEffect or after the component mounts, but with extreme caution, as React re-renders can make the NodeList stale.


Summary

  • document.querySelectorAll("selector") selects all matching elements and returns a static NodeList[1].
  • Use full CSS selectors: tag (p), class (.item), ID (#id), attributes ([type="checkbox"]), and combinations (.item.active, ul > li).
  • Loop through results with forEach to manipulate them (change classes, styles, text, etc.).
  • It is static and supports full CSS selector syntax, unlike getElementsByClassName/tag[1][8].
  • In frameworks like React, direct DOM queries are rare; prefer state/props/refs.

Citations

Sources: Authoritative JS documentation and guides were used, including the Mozilla Developer Network (MDN) for querySelectorAll()[1][12] and examples, and StackOverflow/other tutorials for practical code patterns[11][14].

  1. [1] [2] [3] [4] [5] [6] [7] [10] Document: querySelectorAll() method - Web APIs | MDN
  2. [8] Element: getElementsByClassName() method - Web APIs | MDN
  3. [9] Element: getElementsByTagName() method - Web APIs | MDN
  4. [11] Add Active Class with forEach Loop - JavaScript - Design 2 SEO
  5. [12] Use data attributes - HTML | MDN
  6. [13] [14] javascript - addEventListener on a querySelectorAll() with classList - Stack Overflow
  7. [15] javascript - Is it good practice to manipulate DOM in ReactJS? - Stack Overflow