querySelectorAll(): select elements that match a CSS selector

The `querySelectorAll()` method in JavaScript is used to return a static (non-live) `NodeList` of all elements that match a specified group of CSS selectors within the document.

Table of Contents

  1. Syntax, Parameters, and Return Value
  2. Examples
  3. Notes and Browser Compatibility

Syntax, Parameters, and Return Value

Syntax

elementList = document.querySelectorAll(selectors)
    
  • selectors: A string containing one or more CSS selectors separated by commas. It represents the elements to be selected.

Parameters

  • selectors (string): One or more CSS selectors to match against the document. Multiple selectors can be combined by separating them with commas.

Return Value

  • NodeList: A static NodeList (not a live collection) of elements matching the specified group of selectors. If no matches are found, an empty NodeList is returned.

Examples

Example 1: Selecting All Paragraph Elements

const paragraphs = document.querySelectorAll("p");
console.log(paragraphs.length); // Outputs the number of <p> elements in the document

Example 2: Selecting Elements by Class

const elements = document.querySelectorAll(".my-class");
elements.forEach(element => {
  console.log(element.textContent); // Outputs the text content of each element with class "my-class"
});

Example 3: Selecting Elements by ID

const element = document.querySelectorAll("#my-id");
console.log(element[0]); // Outputs the element with the id "my-id"

Example 4: Selecting Multiple Elements with Different Selectors

const items = document.querySelectorAll("div, p.my-class, span");
items.forEach(item => {
  console.log(item.tagName); // Outputs the tag name of each matched element
});

Notes and Browser Compatibility

Notes

  • The NodeList returned by querySelectorAll() is not live, meaning it does not update automatically if the document structure changes.
  • If you need to select only the first matching element, use the querySelector() method instead.
  • The method is available in all modern browsers and is part of the DOM API.

Browser Compatibility

querySelectorAll() is widely supported across all modern browsers:

  • Chrome: Full support
  • Firefox: Full support
  • Safari: Full support
  • Edge: Full support
  • Internet Explorer 8+: Full support (with some limitations in older versions)

Please browse our website for more documentation and examples. If you need help with the querySelectorAll() function, you can also ask a new question.