4

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

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
Vlad_9996
  • 55
  • 1
  • 3

3 Answers3

9

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:

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>
palaѕн
  • 72,112
  • 17
  • 116
  • 136
2

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); }
});
ponury-kostek
  • 7,824
  • 4
  • 23
  • 31
0

The querySelectorAll function returns a NodeList, not an array.

Convert it to an array using Array.from(nodelist).

jarmod
  • 71,565
  • 16
  • 115
  • 122