I have a example of a situation here, I want to change the color of a div
when clicked. Do I have to have two different functions, one for each div
? What if the functions that I wanted to apply to the div
was very complex? What if I had hundereds of the div
? Can I make a general function, that can be applied for every div
? By this I do not mean for example document.getElementsByClassName(" ... ")
, I want to for example change the color of the separately.
To be clear, how can I apply the same function to different objects? Something like document.getElementThatIsClicked(" ... " )
Thank you.
function changeColor1() {
document.getElementById("div1").style.backgroundColor = "#21a9c9";
}
function changeColor2() {
document.getElementById("div2").style.backgroundColor = "#21a9c9";
}
<div id="div1" onClick="changeColor1()" style="position:absolute; top:10px; left: 10px; width:200px; height: 200px; background-color:#000000;"></div>
<div id="div2" onClick="changeColor2()" style="position:absolute; top: 10px; left: 220px; width:200px; height: 200px; background-color:#000000;"></div>