how to add an eventlistener for every element of a div?

Viewed 49

I'm trying to add a eventlistenner to every element of this div. But I can't seems to able to access every element of this div. The console.log can print out the table as a list. but it shows an error after I try to use forEach method. Why would that be?

let table = document.getElementsByClassName('pixel');
console.log(table);

table.forEach(item => {
    console.log(item)
});

1 Answers

The returned value of table is an HtmlCollection rather than an array so you can't use the Array.prototype.forEach method.

Instead, you can iterate over the divs like so:

let table = document.getElementsByClassName('pixel');
console.log(table);

for (let item of table) {
  console.log(item);
};
<div>
  <div class="pixel">
    P1
  </div>
  <div class="pixel">
    P2
  </div>
</div>

Related