JavaScriptDOM and events

document.querySelectorAll()

Returns a static list (NodeList) of every element that matches a CSS selector.

Returns
A static NodeList with the matching elements (it can be empty).
On this page

Example

#
JavaScript
const lessons = document.querySelectorAll('.lesson')
console.log(lessons.length)

lessons.forEach((lesson, index) => {
  console.log(`${index + 1}. ${lesson.textContent}`)
})

const done = [...document.querySelectorAll('.lesson.done')].map((li) => li.textContent)
console.log(done)
Console
3
1. Intro
2. Tags
3. Attributes
['Tags', 'Attributes']

Definition and usage

#

The querySelectorAll() method works like querySelector(), but returns every matching element in the order they appear in the document. The result is a NodeList object, which has a length property, index access (list[0]), and a forEach() method.

NodeList is not an array: it lacks methods like map(), filter(), or reduce(). You can turn it into an array with Array.from(list) or [...list]. If nothing matches, you get an empty list with a length of 0, not null.

The list is static, meaning it’s a “snapshot” of the document taken at the moment of the call. Elements added later won’t appear in it on their own, and removing elements while iterating over the list is safe.

Syntax

#
Syntax
document.querySelectorAll(selectors)
element.querySelectorAll(selectors)

Parameters

#
  • selectors

    string

    A CSS selector. Separate multiple selectors with commas.

More examples

#
Summing prices from a list
JavaScript
const items = document.querySelectorAll('li[data-price]')

const total = Array.from(items).reduce((sum, item) => sum + Number(item.dataset.price), 0)
console.log(`Total: $${total}`)
Console
Total: $187
The list doesn’t update itself
JavaScript
const list = document.querySelector('#list')
const items = list.querySelectorAll('li')

list.append(document.createElement('li'))

console.log(items.length)
console.log(list.querySelectorAll('li').length)
console.log(list.children.length)
Console
2
3
3

items kept the state from before the element was added. The children property, on the other hand, is a “live” collection that always shows the current children.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Need map() or filter()? Turn the result into an array: [...document.querySelectorAll(".card")].
  • Don’t check the result with if (list). An empty list is still an object, so check list.length.
  • After adding new elements, call the method again, since a previously retrieved list doesn’t change.

Related entries

#

Spotted a mistake or missing an example? Write to us.