Accessing HTMLCollection

242 Views Asked by At

So I am trying to access all of a specific class name and then eventually ad an event listener to them. I'm doing it this way because I am building a hightcharts graph and cannot add click events specifically to the legend items. So after the graph is build I am trying to access the buttons and then add the event listener.

  getButtons() {    
    let buttons = document.getElementsByClassName('legend-btn');
    console.log(buttons);
    console.log(buttons[0]);
  },

The first console.log comes back with an HTMLCollection with a length of 48 (I know very long but for now it's more testing purposes than anything).
The second console.log comes back as undefined. Any ideas why? I was hoping to do something like this:

    for (let i = 0; i < buttons.length; i++) {
      buttons[i].addEventListener('click', function () {
        changebackground(event);
      });
    }

Any suggestions for how I can add the click event for the newly built highcharts graph?

1

There are 1 best solutions below

0
On

May I suggest that you try:

for (let button of buttons) {
  button.addEventListener('click', changebackground);
}

I am not sure why you intended to call changebackground(event): in order to do that, you'd have to put event in the event listener's parentheses. Better pass changebackground directly (assuming it does take an event as a parameter).

I'm not quite sure about what I'm telling you: hard to tell without seeing more of the context.