Home > Blockchain >  Unable to change background color of multiple div onclick using javascript
Unable to change background color of multiple div onclick using javascript

Time:06-24

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>

CodePudding user response:

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 ></div>
<div ></div>
<div ></div>

CodePudding user response:

ID attributes must be unique but as an alternative you could use data-id ( dataset attributes do not need to be unique ) and reference that in whatever javascript function you have. It is simple to assign an event listener to the document and then delegate the event to the target DIV elements as below by inspecting the event.target - thus totally removing the need for ID attributes in the first place. document.getElementById is useful and has it's place - but where there are multiple elements that can be targeted there are better alternatives - querySelectorAll or, as here, delegated events. The same approach could be used if the id were replaced ( as suggested elsewhere ) with a class attribute

document.addEventListener('click',e=>{
  if( e.target!=e.currentTarget && e.target.dataset.id!=null ){
    e.target.classList.toggle('filled')
  }
});
div {
  width: 100px;
  height: 100px;
  border: 1px solid red;
  margin: 10px;
}
.filled{
  background:red
}
<div data-id="main">1</div>
<div data-id="main">2</div>
<div data-id="main">3</div>

  • Related