document. querySelectorAll()
Returns a static list (NodeList) of every element that matches a CSS selector.
- Returns
- A static
NodeListwith the matching elements (it can be empty).
Example
#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)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
#document.querySelectorAll(selectors)
element.querySelectorAll(selectors)Parameters
#selectors
string
A CSS selector. Separate multiple selectors with commas.
More examples
#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}`)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)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()orfilter()? 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 checklist.length. - After adding new elements, call the method again, since a previously retrieved list doesn’t change.
Related entries
#- document.querySelector()Returns the first element that matches a CSS selector, or null when nothing matches.
- Array.from()Creates an array from an iterable or "array-like" object.
- Array.prototype.forEach()Calls a function for every element of the array.
- Element.classListAn object for adding, removing, toggling, and checking an element’s CSS classes.
- Spread (...)The spread syntax spreads an array, string, or object out into individual elements: for copying, merging, and passing arguments.
Spotted a mistake or missing an example? Write to us.