How to: Use a for...of loop to loop over NodeList collected from querySelectorAll
Posted on
According to MDN, it's possible to loop over the items in a NodeList using a for loop, so this should work...
const list = document.querySelectorAll("input[type=checkbox]");
for (const checkbox of list) {
checkbox.checked = true;
}
... well, until this does not work for some reason, e.g. being on a non-supported browser, using JSDOM...
In such case try using Array.prototype.values()
const checkboxNodeList = document.querySelectorAll("input[type=checkbox]");
const checkboxes = [].values.call(checkboxNodeList);
for (const checkbox of checkboxes) {
checkbox.checked = true;
}
You could also use Array.prototype.entries()...
const checkboxNodeList = document.querySelectorAll("input[type=checkbox]");
const checkboxes = [].entries.call(checkboxNodeList);
for (const checkbox of checkboxes) {
checkbox[1].checked = true;
}
...which reveals helpful in case you need the iteration index.
const checkboxNodeList = document.querySelectorAll("input[type=checkbox]");
const checkboxes = [].entries.call(checkboxNodeList);
for (const [i, checkbox] of checkboxes) {
console.log(`Checking checkbox ${i + 1}`);
checkbox.checked = true;
}