3

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 Answers1

4

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>
blex
  • 24,941
  • 5
  • 39
  • 72
notquiteamonad
  • 1,159
  • 2
  • 12
  • 28
  • I changed to for of method. but weirdly. It still can't print out the result. though, this time,It did not show any error message. – user3398356 Mar 26 '20 at 12:57
  • Have you tried swapping out your `console.log` for actually adding the handler? The handler in [this JSFiddle](https://jsfiddle.net/g3mfujk2/) works. – notquiteamonad Mar 26 '20 at 13:26
  • yes,I tried. it worked on w3c web editor and stack overflow's editor. But after i put it back to my code. It weirdly does not work. And it does not show error message. I'm using chrome brower and node.js live-server module. Wonder if that affects the result. – user3398356 Mar 26 '20 at 14:47
  • 1
    I find out what goes wrong. I put the script in the head section. The script gets load before HTML element gets load. – user3398356 Mar 26 '20 at 15:01