Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท DOM: Document and Elements

document.querySelectorAll()

Reference for querySelectorAll(): get every element matching a CSS selector as a static NodeList, loop over it, convert it to an array and avoid common mistakes.

querySelectorAll() returns a NodeList containing every element that matches a CSS selector, in document order. When nothing matches, the list is empty, never null. The list is a static snapshot: elements added or removed later do not change it.

Like querySelector(), it exists on document, on elements and on document fragments.

JavaScript
const items = document.querySelectorAll("ul.menu > li");
for (const item of items) {
  item.classList.add("ready");
}

Try it

Style every match
Static list, array methods

Syntax

JavaScript
document.querySelectorAll(selectors)
element.querySelectorAll(selectors)
Name Description
selectors A string with one selector or a comma-separated selector list. Escape special characters in ids and class names.

Return value: a static NodeList of matching elements in document order. Each element appears once, even if several parts of a selector list match it.

Exceptions: a SyntaxError DOMException if the selector is invalid.

Usage notes

  • It is not an array. A NodeList has length, index access, forEach(), keys(), values(), entries() and is iterable with for...of. It has no map(), filter() or reduce(). Convert with Array.from(list) or [...list] first.
  • Static, unlike getElementsByClassName(). Those older methods return a live HTMLCollection that updates itself. A static list is easier to reason about, especially when you add or remove elements in a loop.
  • Document order, not selector order. "h2, h1" returns headings in the order they appear on the page.
  • Scoped searches only return descendants of the element, but the selector is still matched against the whole document. Start with :scope (el.querySelectorAll(":scope > li")) to match only direct children.
  • Check length, not truthiness. An empty NodeList is still a truthy object.
  • Do not attach one listener per element on large lists. Prefer event delegation.
  • Cost. A broad selector on a huge page walks many nodes. Narrow the starting element when you can.

Browser support

Supported by all current browsers. NodeList.prototype.forEach() is available in every modern browser but not in very old ones, where you convert to an array first.