0

So I have a css grid layout and I am trying to change the Background color for each individual div when you click on it. I have tried searching the forumns and reading the docs, but i keep hitting a wall. Any help would be appreciated.

This is my code so far

var box = document.getElementsByClassName("box");
var testTarget = document.getElementsByClassName("box")[12];

console.log(testTarget);

box.addEventListener("click", () => {
  console.log('hello');
});

and a link to the codepen

https://codepen.io/edubz/pen/BqvxOY?editors=1111

Thank,

edubz

edubz
  • 3
  • 1
  • `getElementsByClassName` returns a collection. You need to loop over the collection and attach the event listener to the individual items. – Turnip Oct 25 '18 at 19:29
  • To access and style the clicked element you would use the event object: https://stackoverflow.com/questions/30786154/javascript-get-clicked-element-addeventlistener – Turnip Oct 25 '18 at 19:35
  • Thank you Turnip – edubz Oct 25 '18 at 19:40

1 Answers1

0

This is the solution for your problem:

var items = document.querySelectorAll(".box");
for (var i = 0; i < items.length; i++) {
  items[i].addEventListener("click", function() {
    this.style.backgroundColor = "red";
  });
}
Zuhair
  • 837
  • 1
  • 8
  • 12