JavaScript Beginner DOM & Async · 7 min read

querySelectorAll and Iterating a NodeList

Lesson 6 of 38 in the JavaScript learning path.

How do I select every matching element and loop them?

querySelectorAll returns every element that matches a CSS selector, packed in a static NodeList. A static list does not grow or shrink if you later add or remove elements. The NodeList has a length and it can be looped, but it is not an array. It has no map, filter, or reduce. Calling map on it throws TypeError in the browser. Array.from builds a real array, and so does spread, because a NodeList is iterable. for...of walks the NodeList directly and does not require a copy.

Use the direct loop when you only need to touch each node, such as adding a counted class. Use Array.from when you want array methods, such as mapping each item to its trimmed text. Build the visible result with createElement and textContent. Joining the labels into an HTML string and assigning that string with innerHTML would parse student text as markup, which is a separate bug from the loop itself.

Syntax & Parameters

Syntax
const nodes = document.querySelectorAll(selector);
for (const node of nodes) {}
const list = Array.from(nodes);
const copy = [...nodes];

Example

Interactive preview available
app.js
'use strict';

const nodes = document.querySelectorAll('#topic-list > li');
let mapFailed = false;
try {
  nodes.map((node) => node.textContent);
} catch (error) {
  mapFailed = error instanceof TypeError;
}

const asArray = [...nodes];
const labels = Array.from(nodes, (node) => node.textContent.trim());
for (const node of nodes) {
  node.classList.add('is-counted');
}

const list = document.querySelector('#label-list');
if (list !== null) {
  list.replaceChildren();
  for (const label of labels) {
    const item = document.createElement('li');
    item.textContent = label;
    list.append(item);
  }
}

const report = [
  `nodeListIsArray: ${Array.isArray(nodes)}`,
  `copiedIsArray: ${Array.isArray(asArray)}`,
  `mapFailed: ${mapFailed}`,
  `count: ${nodes.length}`,
  `labels: ${labels.join(', ')}`,
].join('\n');

const summary = document.querySelector('#topic-summary');
if (summary !== null) {
  summary.textContent = report;
}
console.log(report);

Expected Output

Console and #topic-summary:

nodeListIsArray: false
copiedIsArray: true
mapFailed: true
count: 4
labels: Scope, Arrays, Events, Fetch

#label-list text:
Scope
Arrays
Events
Fetch

Line-by-Line Walkthrough

  1. querySelectorAll collects every li that is a direct child of #topic-list into a static NodeList.
  2. The try calls map on that NodeList. Browsers do not provide map there, so the catch records a TypeError.
  3. Spread copies the NodeList into asArray, which is a real array, and Array.isArray on the original list stays false.
  4. Array.from walks the same nodes and returns a new array of trimmed label strings, using the map function argument.
  5. for...of visits each node in the NodeList and adds the class is-counted without converting the list first.
  6. The result list is cleared with replaceChildren so a second run would not duplicate labels.
  7. Each label becomes its own li through createElement, and textContent stores the label as text.
  8. The items are appended one by one. No HTML string is built for the loop result.
  9. The report records whether each value is an array, whether map failed, the count, and the joined labels.
  10. The report is written to #topic-summary with textContent and printed to the console.

Common Pitfalls & Security

A NodeList can look like an array because it has a length and numeric indexes, but array methods are not on its prototype. forEach exists on NodeList in current browsers, and map does not, so code that works on an array of strings fails on the selector result. querySelectorAll is static: nodes added after the call are absent until you select again. getElementsByClassName is different. That collection is live. Writing the loop result as HTML also crosses into XSS when a label is student text.

  • nodes.map throws TypeError. Convert with Array.from or spread before you call map, filter, or reduce.
  • list.innerHTML = labels.join("") parses markup. A label equal to the untrusted string <img src="x" alt="untrusted"> becomes an image and is an XSS hole. Create elements and set textContent.
  • A live HTMLCollection changes while you loop if you remove nodes. Prefer the static NodeList from querySelectorAll for a snapshot.
  • Spreading a NodeList copies elements, not deep clones. Editing text on the copy still edits the live node.
  • An empty NodeList is still a successful result. length 0 is not null, and the loop body simply does not run.

Best Practices & Modern Standards

Select with the narrowest selector that still means every node you want, such as a direct child combinator, so nested lists are not included by accident. Loop with for...of when you will touch each node in place, and convert with Array.from when you need map or filter. ES2024 does not turn a NodeList into an array. The conversion stays explicit, which keeps the cost visible.

Render the derived list with createElement and textContent, then append those nodes. If you will insert many of them, a DocumentFragment can hold them first. Keep the source NodeList read-only from the point of view of your data: add a class if you must, but build new text nodes for any string a student could have typed.

Real-World Use

A course syllabus shows a topic list, and a progress widget needs every topic label in a second column. querySelectorAll reads the items once. for...of marks each source item as counted, and Array.from builds the plain labels for the summary. The second column is new elements, so the widget can reorder or filter labels later without rewriting the syllabus markup.

The map failure is the guard rail. A future edit that calls map on the NodeList stops in the catch instead of failing halfway through a paint. The summary then shows the count a teacher expects: four topics, copied into a real array, with the original list left as a NodeList.

Frequently Asked Questions

Is a NodeList an array?

No. Array.isArray returns false for a NodeList. It is an iterable collection with a length. Convert it with Array.from or spread when you need map, filter, or reduce.

Should I use for...of or Array.from?

Use for...of to visit each node and change it in place, such as adding a class. Use Array.from when the result should be an array of values, such as trimmed labels. Both work on the NodeList because it is iterable.

Does the list update if I add a topic later?

No. The NodeList from querySelectorAll is static. Elements added after the call are not inserted into that list. Select again, or keep your own array, when the syllabus can grow.

Why not join the labels into HTML?

A joined HTML string is parsed when it is assigned to innerHTML. Topic text that contains a tag becomes a real element, which is an XSS hole if any label is untrusted. Put each label in textContent instead.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…