Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to change background color of multiple div onclick using javascript

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading