JavaScript Document querySelectorAll() Method

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance method

What You’ll Learn

document.querySelectorAll() is an instance method that returns a static NodeList of every element matching a CSS selector string (see MDN Document: querySelectorAll()). Learn multiple selectors, attribute lookups, forEach loops, SyntaxError / CSS.escape() handling, how it compares to querySelector() and live collections, and five try-it labs.

01

Kind

Instance method

02

Arg

CSS selectors

03

Returns

static NodeList

04

Match

All matches

05

Throws

SyntaxError

06

Status

Baseline

Introduction

Where querySelector stops at the first hit, querySelectorAll collects every match into a list you can loop. Pass the same CSS selector language you already know from stylesheets.

MDN: the result is a static (not live) NodeList in document order — parents before children, earlier siblings before later ones. No matches means an empty list (not null). If the selector includes a CSS pseudo-element, the list is always empty.

💡
Think: “CSS find — every hit”

1) Write a valid CSS selector (e.g. "p" or ".note, .alert")
2) Call document.querySelectorAll(selector)
3) Check length or loop with forEach
4) Remember the list does not update if the DOM changes later

Related tutorials: querySelector(), Element.querySelectorAll(), getElementsByClassName(), getElementById().

Understanding document.querySelectorAll()

An instance method on the page’s document object (ParentNode mixin) that looks up all matching elements (MDN).

  • selectors — a valid CSS selector string; invalid syntax throws SyntaxError (MDN).
  • Return value — static NodeList of matching Elements, or empty if none (MDN).
  • Order — document order (MDN).
  • Static — not live; later DOM changes do not update the list (MDN).
  • Pseudo-elements — always yield an empty list (MDN).
  • Escape special ids — use CSS.escape() when needed (MDN).

📝 Syntax

General form of Document.querySelectorAll (MDN):

JavaScript
querySelectorAll(selectors)

Parameters

  • selectors — a string containing one or more selectors to match. Must be valid CSS; otherwise a SyntaxError is thrown (MDN). Escape class/id values that are not valid CSS identifiers with CSS.escape() (MDN).

Return value

A non-live NodeList with one Element per match, or an empty NodeList when nothing matches (MDN). Elements are in document order (MDN).

Exceptions

  • SyntaxError DOMException — thrown if the selector syntax is invalid (MDN).

Common beginner patterns

JavaScript
document.querySelectorAll("p");
document.querySelectorAll("div.note, div.alert");
document.querySelectorAll("iframe[data-src]");

const items = document.querySelectorAll(".card");
items.forEach((el) => {
  el.classList.add("is-ready");
});

⚡ Quick Reference

GoalCode
All paragraphsdocument.querySelectorAll("p")
Multiple classesdocument.querySelectorAll("div.note, div.alert")
Attribute presentdocument.querySelectorAll("iframe[data-src]")
Loop matcheslist.forEach((el) => { ... })
Count matchesdocument.querySelectorAll(".card").length
Escape special iddocument.querySelectorAll("#" + CSS.escape(id))
MDN statusBaseline Widely available (since Jul 2015)

🔍 At a Glance

Four facts about document.querySelectorAll().

Returns
NodeList

static

Arg
selectors

CSS string

No match
empty list

length 0

Status
Baseline

since 2015

📋 Common pitfalls

SituationResultFix
No matchEmpty NodeList (MDN)Check length if needed
Invalid selector stringSyntaxError (MDN)Fix CSS syntax / escape values
Expect live updatesList stays frozen (MDN)Call again after DOM changes
Want only the first matchYou get every matchUse querySelector()
CSS pseudo-element selectorAlways empty list (MDN)Select real elements instead

Examples Gallery

Examples follow MDN Document: querySelectorAll() and practical beginner patterns.

📚 Getting Started

MDN’s core lookups: tag names and selector groups.

Example 1 — MDN: list of all <p> elements

Obtain a NodeList of every paragraph in the document.

JavaScript
const matches = document.querySelectorAll("p");
console.log("paragraph count:", matches.length);
console.log("first text:", matches[0] ? matches[0].textContent : "(none)");
Try It Yourself

How It Works

Index with [0], [1], … or read length. An empty result still returns a list object (MDN).

Example 2 — MDN: match note or alert

Comma-separated selectors return elements matching any of the groups.

JavaScript
const matches = document.querySelectorAll("div.note, div.alert");
console.log(
  Array.from(matches).map((el) => el.className).join(", ")
);
Try It Yourself

How It Works

Document order is preserved across both selector branches (MDN).

📈 Practical Patterns

Attributes, looping, and choosing first-match vs all-matches.

Example 3 — MDN: attribute selector

Find every iframe that has a data-src attribute.

JavaScript
const matches = document.querySelectorAll("iframe[data-src]");
console.log("lazy iframes:", matches.length);
matches.forEach((frame) => {
  console.log(frame.getAttribute("data-src"));
});
Try It Yourself

How It Works

Attribute selectors are pure CSS — same power as in stylesheets (MDN).

Example 4 — MDN: access matches with forEach

Loop the NodeList like an array-style collection.

JavaScript
const highlightedItems = document.querySelectorAll(".highlighted");

highlightedItems.forEach((item) => {
  item.classList.add("processed");
});

console.log("processed:", highlightedItems.length);
Try It Yourself

How It Works

MDN notes you can examine the list like an array. Modern browsers support NodeList.prototype.forEach.

Example 5 — querySelectorAll vs querySelector

Same selector, different return shapes.

JavaScript
const first = document.querySelector(".card");
const all = document.querySelectorAll(".card");

console.log("first tag:", first ? first.tagName : "null");
console.log("all length:", all.length);
console.log("same first node:", first === all[0]);
Try It Yourself

How It Works

Use querySelector() when one node is enough; use querySelectorAll when you need the full set.

🚀 Common Use Cases

  • Bulk UI updates — add a class to every .card or button.
  • Mixed selector groupsdiv.note, div.alert in one call (MDN).
  • Attribute filtersiframe[data-src], li[data-active='1'] (MDN).
  • Scoped searches — find a container, then call Element.querySelectorAll() inside it (MDN).
  • Snapshot lists — static NodeList is safe to iterate while mutating the DOM.
  • Need only one? — prefer querySelector() (MDN).

🧠 How querySelectorAll() Builds a List

1

Parse the selector string

Invalid CSS throws SyntaxError; valid CSS continues (MDN).

selectors
2

Collect every match

Walk the document and gather elements that match any selector group (MDN).

All matches
3

Freeze a static NodeList

Document order; not live. Empty list if nothing matched (MDN).

static
4

Loop and update

Use forEach, for...of, or index access on the list.

📝 Notes

  • MDN: Baseline Widely available since July 2015.
  • Not Deprecated, Experimental, or Non-standard.
  • MDN: returns a static NodeList — not live.
  • MDN: CSS pseudo-elements always produce an empty list.
  • MDN: escape class/id values that are not valid CSS identifiers.
  • Related: querySelector(), Element.querySelectorAll(), getElementsByClassName().

Browser Support

Document.querySelectorAll() is Baseline Widely available on MDN (across browsers since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Document.querySelectorAll()

CSS-powered all-match DOM lookup — static NodeList across all major browsers.

Baseline Widely available
Google Chrome 1+
Yes
Mozilla Firefox 3.5+
Yes
Apple Safari 3.1+
Yes
Microsoft Edge 12+
Yes
Opera 10+
Yes
Internet Explorer 9+
Yes
querySelectorAll() Wide

Bottom line: Use querySelectorAll when you need every match. Prefer querySelector for a single node, and remember the NodeList is static.

Conclusion

document.querySelectorAll(selectors) is the everyday way to collect every element that matches a CSS selector into a static NodeList. Loop with forEach, check length when needed, escape special ids, and fall back to querySelector when one node is enough.

Continue with releaseCapture(), Element.querySelectorAll(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use forEach / for...of to process matches (MDN)
  • Prefer specific selectors that match your intent
  • Use querySelector() when you only need the first hit
  • Call again after DOM changes if you need a fresh snapshot
  • Escape dynamic special ids with CSS.escape() (MDN)

❌ Don’t

  • Assume the list updates live like getElementsByClassName
  • Pass invalid CSS without try/catch
  • Expect CSS pseudo-elements to return nodes (MDN)
  • Confuse empty list with null
  • Use a huge document-wide scan when a scoped element search is enough

Key Takeaways

Knowledge Unlocked

Five things to remember about querySelectorAll()

CSS-powered all-match lookup — static NodeList.

5
Core concepts
🗂02

Match

all matches

CSS
⚠️03

Invalid

SyntaxError

MDN
📋04

No match

empty list

length 0
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

MDN: Document.querySelectorAll() returns a static (not live) NodeList of the document’s elements that match the specified group of CSS selectors.
No. MDN marks Document.querySelectorAll() as Baseline Widely available (across browsers since July 2015). It is not Deprecated, Experimental, or Non-standard.
You get an empty NodeList (length 0), not null (MDN). Still safe to call forEach — it simply runs zero times.
MDN: it is static (non-live). It does not automatically update when the DOM changes after the call.
querySelector() returns the first matching Element or null. querySelectorAll() returns every match in a NodeList (empty when none).
A SyntaxError DOMException is thrown if selectors is not a valid CSS selector string (MDN). Escape special class/id values with CSS.escape().
Did you know?

Because the NodeList is static, you can safely remove or move nodes while looping without the list shifting under you mid-iteration — a common gotcha with live HTMLCollection APIs like getElementsByClassName().

Next: releaseCapture()

Learn the Non-standard Document.releaseCapture() mouse capture release API and its Pointer Events alternative.

releaseCapture() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful