How to Use querySelectorAll in JavaScript: Syntax and Examples
Use
document.querySelectorAll(selector) to select all elements matching a CSS selector. It returns a static NodeList of elements you can loop through or access by index.Syntax
The querySelectorAll method takes a CSS selector string and returns a static list of all matching elements in the document.
document: The web page document object.querySelectorAll(selector): Method to find all elements matching the selector.selector: A string with any valid CSS selector (e.g., class, id, tag).- Returns a NodeList of elements, which is like an array but not exactly.
javascript
const elements = document.querySelectorAll('selector');
Example
This example selects all paragraphs with the class highlight and logs their text content.
javascript
const highlights = document.querySelectorAll('p.highlight'); highlights.forEach((el, index) => { console.log(`Paragraph ${index + 1}: ${el.textContent}`); });
Output
Paragraph 1: This is the first highlighted paragraph.
Paragraph 2: This is the second highlighted paragraph.
Common Pitfalls
One common mistake is expecting querySelectorAll to return a live list that updates automatically. It returns a static NodeList, so changes in the DOM after selection won't appear in the list.
Another mistake is treating the NodeList exactly like an array. It supports forEach but not all array methods like map or filter without conversion.
javascript
/* Wrong: expecting live updates */ const items = document.querySelectorAll('.item'); document.body.innerHTML += '<div class="item">New Item</div>'; console.log(items.length); // Still old count /* Right: re-select after DOM changes */ const updatedItems = document.querySelectorAll('.item'); console.log(updatedItems.length); // Updated count
Output
3
4
Quick Reference
- Selector: Use any valid CSS selector string.
- Returns: Static NodeList of matching elements.
- Access: Use
forEachor index to loop/access elements. - Note: NodeList is not a full array; convert with
Array.from()if needed.
Key Takeaways
Use document.querySelectorAll('selector') to get all matching elements as a static NodeList.
Loop through results with forEach or access by index; convert to array if you need array methods.
querySelectorAll returns a snapshot, so it does not update if the DOM changes later.
The selector string supports any valid CSS selector like classes, IDs, tags, or attribute selectors.
Re-run querySelectorAll if you need to get updated elements after DOM changes.