0

I have a question about foreach and subsequent capture of clicks.

When I use foreach like this, it works.

 let buttons = document.getElementsByClassName('button');
    
    for (let oneButton of buttons) {
        oneButton.addEventListener('click',function(){
            console.log('ahoj');
        })
    }

If I use it, but this is how it will write me a error: Uncaught TypeError: buttons.forEach is not a function

buttons.forEach(function(oneButton){
        oneButton.addEventListener('click',function(){
            console.log('Zdarec')
        })
    })

Can anyone explain to me why this tells me that forEach is not a function? It is clear to me that I can use the first option and move on, but I would like to know why the second option does not work.

I tried searching the internet, but I didn't find anything.

I will be happy for any answer.

Thanks :-)

  • 1
    Because `document.getElementsByClassName` does not return an array. https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName – tkausl Apr 28 '22 at 06:27
  • [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList) like `querySelectorAll` supports `forEach`. `let buttons = document.querySelectorAll('.button'); buttons.forEach(...` would work fine therefore. – Lain Apr 28 '22 at 06:48

0 Answers0