How to loop through selected elements with document.querySelectorAll
Loop over elements with document.querySelectorAll()
using forEach()
:
Just swap 'selector' with your actual CSS selector to engage the loop.
The essentials of looping with array conversion
The spread syntax can convert a NodeList to an array:
This endows your codebase with the power of additional array methods like map
, filter
, and reduce
.
For loop: The classic way to iterate over NodeList
A for loop allows NodeList iteration sans conversion:
This serves you the full authority over the iteration process, enabling conditional checks, breaks, or continues as required.
Older browsers? We got alternatives!
On older browsers that do not support forEach
on NodeLists, either polyfill or apply the following code:
This strategy employs forEach
of an array prototype and utilises it directly on a NodeList.
Cross-browser compatibility: Remember the ES5 fellas!
For enhanced browser compatibility, especially in the absence of polyfills, consider transpiling modern JavaScript back to good old ES5 with tools like Babel.js.
Elements validation: Look before you leap!
Validate that the NodeList is holding the expected elements before executing the loop:
This precautionary step shields you from the aftermath of carrying out actions on unwanted or empty selections.
The falsy trap: Just truthy things!
While assigning values in loops, ensure you avoid skipping falsy elements:
Guarding against undefined or null elements in the NodeList can save you some bug-hunting hours!
Browser environment: When it matters!
Plan your solutions to be compatible across all the target browsers. Before using methods on NodeLists, ensure compatibility:
When a browser refuses to age!
Sometimes, you have to polyfill NodeList.prototype.forEach
for older browsers. Script inclusions or sourcing from a Polyfill.io service should help.
Was this article helpful?