1

I am trying to learn javascript and i made a grid with some boxes in it and i'm trying to change the color of the grid box when i click on it. I know i can use jquery i did it and worked but i want to do this with javascript only so this is my code so far:

var grid = document.getElementsByClassName('box');

function changeColor(item) {
  item.addEventListener('click', function() {
    this.style.background = 'black';
  });
};

grid.forEach(function(el) {
  changeColor(el);
});

I feel like this needs 'bind' method and i dont know how bind works yet so is it possible to make it work without bind? Thank you.

Reşit Körsu
  • 578
  • 3
  • 8
  • 18

2 Answers2

4

You don't have to declare a separate function. You can just catch all the elements with box class, then iterate over them with forEach() function and bind a click event to every element.

Note: grid variable isn't an array. It's an array-like object. To be able to use forEach() function over it, you have to use Array#from to change it into an array.

var grid = document.getElementsByClassName('box');

Array.from(grid).forEach(v => v.addEventListener('click', function() {
  v.style.background = 'black';
}));
.box {
  height: 100px;
  width: 100px;
  background: lightgreen;
  margin: 5px;
}
<div class='box'></div>
<div class='box'></div>
kind user
  • 40,029
  • 7
  • 67
  • 77
2

The line grid.forEach is invalid. If you open your browser's developer console, you should see it raises a TypeError. If you run console.log(grid), you'll see that grid is an HTMLCollection, and that can't be iterated over using forEach.

You can convert grid to an Array first with Array.from(grid), or use [].forEach.call(grid, changeColor)

Community
  • 1
  • 1
codehearts
  • 483
  • 1
  • 9
  • 16