3

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
  • 16,804
  • 3
  • 16
  • 39
Vlad_9996
  • 45
  • 1
  • 3

3 Answers3

6

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ѕн
  • 68,816
  • 17
  • 108
  • 129
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,355
  • 4
  • 20
  • 28
0

The querySelectorAll function returns a NodeList, not an array.

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

jarmod
  • 59,580
  • 13
  • 95
  • 104