0

I made a List of buttons of class 'bol':

const bollen = document.querySelectorAll('button.bol');

With console.log(bollen) I get: [button.bol.bolkleur, button.bol.bolkleur, button.bol.bolkleur, button.bol.bolkleur]

I make a click event listener and want to know what is the index in the list of the item that I clicked but get the error : Uncaught TypeError: bollen.indexOf is not a function. But I don't understand why because I have seen examples that seem the same. My code is the following:

bollen.forEach(function (bol) {
    bol.addEventListener('click', function (e) {
        const gekozenBol = bollen.indexOf(bol);
        console.log(`gekozen bol is ${gekozenBol}`);
    });
});

Who can help me see what I do wrong? I am limited to a set of code because the project have to be made with things we have learned. Thankyou

Johan Belien
  • 59
  • 1
  • 8
  • 1
    `querySelectorAll` returns a NodeList, not an array. So, it doesn't have an `indexOf` method. Why do you even need to lookup the index of an element? – VLAZ May 11 '21 at 18:11
  • @VLAZ it is for a carousel. If you click one of the dots below the carousel I want to get the index to choose the image that is chosen. But what is the alternative for a nodelist then? And why is it different to an array, since it is also a list of elements of the same type? Sorry for the silly questions. – Johan Belien May 11 '21 at 18:18
  • An array has some methods like `.indexOf` and `.map`. A NodeList doesn't. Both still have indexes for elements and NodeLists also have a `.forEach` but are simply not the same kind of object. I still don't really understand why you need the index, though - you *have a direct reference to the image*. – VLAZ May 11 '21 at 18:21
  • @VLAZ thankyou, thanks to your comment I realized that it was not the same as an array. So I did it with a for iteration and it works!. Well I don't have acces to the image because I don't click the image but some dots that represent an image. I have to checkout which of the dots I clicked to search the image that is represented by the dot. Thankyou anyway, it works now. – Johan Belien May 11 '21 at 18:44
  • @VLAZ today I understand your remark about the index better ;-). Till now I never catched the index with a forEach. Only the element. Just today I discovered that I had to add the index in the forEach. Thankyou that your idea did let me think about it and discover. – Johan Belien May 12 '21 at 11:53

0 Answers0