Explain Codes LogoExplain Codes Logo

How to loop through selected elements with document.querySelectorAll

javascript
array-methods
node-list
browser-compatibility
Alex KataevbyAlex Kataev·Nov 16, 2024
TLDR

Loop over elements with document.querySelectorAll() using forEach():

document.querySelectorAll('selector').forEach(el => { // Time to play with the element! });

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:

[...document.querySelectorAll('selector')].forEach(el => { // We're free to frolic with all array methods now! });

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:

const nodes = document.querySelectorAll('selector'); for(let i = 0; i < nodes.length; i++) { // nodes[i] is now our playground! }

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:

Array.prototype.forEach.call(document.querySelectorAll('selector'), function(el){ // Each element just got a 'forEach' joyride! });

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:

const allCheckboxes = document.querySelectorAll('input[type="checkbox"]'); if(allCheckboxes.length === 0) { console.error('Alert! No checkboxes found yet! Time to uncheck your expectations!'); }

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:

for(let checkbox of allCheckboxes) { if(checkbox) { // checkbox has spoken the truth! Proceed! } }

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:

- `.forEach` is a myth for the Internet Explorer. - The spread operator is an ES6 feature, not everyone is as cool as ES6.

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.