0

I have lots of small squares which have a class of "newDiv". I want to change their background color to black when mouse cursor are on them. However, I want them to stay the same(backgroundcolor black) even when mouse cursor is out. I'm trying to make my code work but I always get a syntax error or it does not work at all.

I've altered the code, tried to fix syntax etc.

black = true;
let tiles = document.getElementsByClassName('newDiv');



tiles.forEach(tile => {
tile.addEventListener('mouseover', function(e){
  if(black){
  tile.style.backgroundColor = "black";
  }
}) 
}

Uncaught syntax error missing ) after argument list tiles.forEach is not a function.

tosyn
  • 57
  • 6

4 Answers4

4

It's because tiles isn't an array. It looks like one but it is actually a HTMLCollection.

You can fix this by either converting to Array with Array.from():

let tiles = Array.from(document.getElementsByClassName('newDiv'));

Or using a for loop instead:

for (const tile of tiles) {
  tile.addEventListener('mouseover', e => {
    tile.style.backgroundColor = "black";
  });
}

Soc
  • 7,425
  • 4
  • 13
  • 30
1

I did this and it worked for me. And as @Omer said tiles is not an array.

var black = true;
var tiles = document.getElementsByClassName('newDiv');

for(var tile of tiles){
tile.addEventListener('mouseover', function(e){
  if(black){
    this.style.backgroundColor = "black";
  }
}
);
}
Fabio Assuncao
  • 624
  • 4
  • 12
  • Since I'm a beginner I do not know this kind of loop very well. What is tile of tiles? Is it another variable that we used to store this loop's output? – tosyn Sep 12 '19 at 07:01
  • This will store each element of tiles you can check the explanation here too(for...in statement) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration – Fabio Assuncao Sep 12 '19 at 07:06
0

Because You acctually missed an ')'; It would be better if you use arrow function :)

let black = true;
let tiles = document.getElementsByClassName('newDiv');

tiles.forEach(tile => {
tile.addEventListener('mouseover', e =>{
  if(black){
    tile.style.backgroundColor = "black";
  }
}) 
})

In addition, as written in this answer - you used an html collection an not an array.

user1452221
  • 124
  • 2
  • 9
0

getElementsByClassName() results in an HTMLCollection, which cannot be iterated with a forEach(). Try using a simple for-Loop or jQuerys $.each()-Function. Here is a fiddle.

let tiles  = document.getElementsByClassName('newDiv');

for (let i = 0; i < tiles.length; i++) {
    tiles[i].addEventListener('mouseover', function(e){
    tiles[i].style.backgroundColor = "black"});
}
PftM
  • 148
  • 1
  • 6