I have a simple question, what simplest method do you know to replace the method some for NodeList? This some method is only for Array prototype.
I have currently come up with the rather outlandish idea of iterating and holding a boolean in a variable, however I would like to know your point of view.
My obscure approach
const toCheck = (elem) => elem.checked;
const methodSome = (list, fn) => {
let result = false;
for (let i = 0; i < list.length; i++) {
if (fn(list[i])) {
result = true;
break;
}
}
return result;
};
const elems = document.querySelectorAll(`[name="something"]`);
const hasBeenChecked = methodSome(elems, toCheck);
As others have mentioned, the spread operator can put elements into an array.
A simpler approach is to use the :checked pseudo-class selector with a call to document.querySelector() (instead of using document.querySelectorAll()). The Double NOT operator !! can be used to convert the element to a boolean.
const hasBeenChecked = !!(document.querySelector(`[name="something"]:checked`));
With this approach there is no need to put elements into an array and have a function with a loop to check those elements.
See an example here:
const hasBeenChecked = !!(document.querySelector(`[name="something"]:checked`));
console.log('hasBeenChecked: ', hasBeenChecked);
<div><input type="checkbox" name="something" /> something?</div>
<div><input type="checkbox" name="something" checked /> something?</div>
<div><input type="checkbox" name="something" /> something?</div>
<div><input type="checkbox" name="something" checked /> something?</div>
Use the spread operator to convert a NodeList to an Array
const hasBeenChecked = [...elems].some(toCheck);
Convert it to an array first:
With spread operator:
const toCheck = (elem) => elem.checked;
const methodSome = (list, fn) => {
let result = false;
for (let i = 0; i < list.length; i++) {
if (fn(list[i])) {
result = true;
break;
}
}
return result;
};
const elems = document.querySelectorAll(`[name="something"]`);
const hasBeenChecked = [...elems].some(toCheck);
With Array.from
const toCheck = (elem) => elem.checked;
const methodSome = (list, fn) => {
let result = false;
for (let i = 0; i < list.length; i++) {
if (fn(list[i])) {
result = true;
break;
}
}
return result;
};
const elems = document.querySelectorAll(`[name="something"]`);
const hasBeenChecked = Array.from(elems).some(toCheck);