DOM Node Lists
A NodeList is the array-like returned by querySelectorAll and a few legacy properties. It supports forEach, but not the full Array vocabulary.
What NodeList gives you out of the box
| Property / method | What it does |
|---|---|
length | Number of nodes. |
item(i) | Same as bracket access. |
forEach((node, index, list) => …) | Iterate. |
entries() / keys() / values() | Iterators for for…of. |
Get Array methods
JS
const items = document.querySelectorAll("li");
// Spread or Array.from convert to a real array
const titles = [...items].map(li => li.textContent);
const ready = Array.from(items).filter(li => li.matches(".ready"));
// for…of works directly
for (const item of items) console.log(item);
// forEach with index
items.forEach((li, i) => li.dataset.index = i);
NodeList vs. Array — the lookalikes
JS
const list = document.querySelectorAll("li");
Array.isArray(list); // false
list.map; // undefined — no map
[...list].map; // works
list instanceof NodeList; // true
Note:
childNodes returns a live NodeList — modifying the DOM changes it on the fly. querySelectorAll returns a static one — safer for loops.Tip: If you'll do more than iterate, spread to an array first:
const items = [...document.querySelectorAll("li")]. You get the full Array API and avoid live-list surprises.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from DOM Node Lists!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Iterate a NodeList directly with the supported method.
document.querySelectorAll('li').
(li => li.classList.add('ready'));
Seven letters.
Discussion
Loading…