0

I'm trying to create a timetable site for myself to practice CSS grid and Javascript, I would like to be able to select the 'completed?' section of the timetable and change the div's colour to green. However, I'm having no luck.. so far my code is:

document.getElementsByClassName('tick').onclick = changeBgColor;
function changeBgColor() {
  document.getElementsByClassName('tick').style.backgroundColor = "green";
}
<div class="item tick complete1"></div>
<div class="item tick complete2"></div>
<div class="item tick complete3"></div>
<div class="item tick complete4"></div>
<div class="item tick complete5"></div>
<div class="item tick complete6"></div>
<div class="item tick complete7"></div>

Any help would be appreciated!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

0

You need to loop through all the elements for adding the click event listener. Also use this.style.background = "green"; to change the background color inside click function.

var elem = document.getElementsByClassName('tick');
for(var i=0; i<elem.length; i++){
  elem[i].addEventListener('click', changeBgColor);
}

function changeBgColor() {
 this.style.background = "green";
}
 <div class="item tick complete1">1</div>
 <div class="item tick complete2">2</div>
 <div class="item tick complete3">3</div>
 <div class="item tick complete4">4</div>
 <div class="item tick complete5">5</div>
 <div class="item tick complete6">6</div>
 <div class="item tick complete7">7</div>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

document.getElementsByClassName returns a collection.Loop over this collection after converting using the spread operator.Use forEach to loop over this array and use addEventListener to add click event

[...document.getElementsByClassName('tick')].forEach(function(item) {
  item.addEventListener('click', changeBgColor)
})


function changeBgColor() {
  this.style.backgroundColor = "green";
}
<div class="item tick complete1">1</div>
<div class="item tick complete2">2</div>
<div class="item tick complete3">3</div>
<div class="item tick complete4">4</div>
<div class="item tick complete5">5</div>
<div class="item tick complete6">6</div>
<div class="item tick complete7">7</div>
brk
  • 48,835
  • 10
  • 56
  • 78