I have a problem with the method array.some() in JavaScript. I have an html-code:
<div class="list">
<div class="item"></div>
<div class="item"></div>
<div class="item selected"></div>
</div>
And I'm trying to find one element of array which contains class-name "selected".
const items = document.querySelectorAll('.item');
items.some(item => {
if (item.classList.contains('selected')) { console.log(true); }
else { console.log(false); }
});
But all what I get is this error: "Uncaught TypeError: items.some is not a function" Can someone tell me, why the method Array.some() doesn't work for div array? Thank you
This happens because .some() is an array method but items here is not an array but a collection of nodes, better known as NodeList. So, we first need it to convert it into an array like:
const items = [...document.querySelectorAll('.item')];
For more info:
document.querySelectorAll()DEMO:
const items = [...document.querySelectorAll('.item')];
items.some(item => {
if (item.classList.contains('selected')) {
console.log(true, item);
} else {
console.log(false, item);
}
});
<div class="list">
<div class="item"></div>
<div class="item"></div>
<div class="item selected"></div>
</div>
document.querySelectorAll returns NodeList witch don't implement some method
Use Array.from to convert NodeList to Array
You can find other methods to convert NodeList to Array
const items = Array.from(document.querySelectorAll('.item'));
items.some(item => {
if (item.classList.contains('selected')) { console.log(true); }
else { console.log(false); }
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With