querySelectorAll & forEach
querySelectorAll & forEach in Modern JavaScript
Selecting and manipulating collections of DOM nodes is a cornerstone of client-side web development. While single-element selectors like getElementById() or querySelector() return either an Element or null, document.querySelectorAll() matches all DOM elements satisfying a standard CSS selector and returns a static NodeList.
1. querySelector vs. querySelectorAll
Understanding the return types and behavioral differences is vital:
| Feature | querySelector() | querySelectorAll() | getElementsByClassName() |
|---|---|---|---|
| Return Type | Single Element or null | Static NodeList | Live HTMLCollection |
| Selector Syntax | Any CSS selector | Any CSS selector | Class name string only |
| Iteration Support | N/A (Single node) | Native .forEach() | Requires conversion to Array |
| DOM Mutation Effect | No effect on variable | Snapshot (Static) | Live updates with DOM changes |
2. Iterating with NodeList.prototype.forEach
Modern browsers support .forEach() directly on NodeList instances, enabling clean functional iteration without manual for loops.
3. NodeList vs. HTMLCollection vs. Array
A NodeList is not an Array. While modern NodeList has .forEach(), it lacks array transformation methods like .map(), .filter(), .reduce(), or .some().
Converting NodeList to an Array
To leverage array transformations, convert the NodeList using the spread operator or Array.from():
4. Static vs. Live Collections
querySelectorAll() returns a static snapshot. Changes to the DOM after the query will not be reflected in the existing NodeList:
5. Practical Example: Tab Controller
Practice Quiz
Traversing DOM Nodes
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Immediately Invoked Functions (IIFE) | Traversing DOM Nodes |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.