Advertisements
Unable to change background color of multiple div onclick using javascript. I used for loop but still not working. Unable to change background color of multiple div onclick using javascript. I used for loop but still not working. Unable to change background color of multiple div onclick using javascript. I used for loop but still not working.
function abc(){
var a = document.getElementById("main");
for(i=0;i<a.length;i++){
a[i].onclick= function(){
a[i].style.backgroundColor="red";
}
}
}
abc();
div{
width: 100px; height: 100px; border: 1px solid red; margin: 10px;
}
<div id="main">
</div>
<div id="main">
</div>
<div id="main">
</div>
>Solution :
IDs are unique. Use a class instead.
let boxes = document.getElementsByClassName("box");
for (let i = 0; i < boxes.length; i++) {
boxes[i].addEventListener("click", () => {
event.target.classList.add("bg-red");
})
}
.box{
width: 100px;
height: 100px;
border: 1px solid red;
margin: 10px;
}
.bg-red{
background-color: red;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>