Call onClick Function On Multiple Elements
Solution 1
You can pass the id of the div being clicked on your changeClass function:
<div id="card3" class="block" onclick="changeClass(this.id)">
This way, it will be easier to handle your class switching process:
function changeClass(id) {
var div = document.getElementById(id);
switch (id) {
case "card2": {
if (div.className == "className") {
div.className = "anotherClassName";
}
break;
}
case "card3": {
if (div.className == "block") {
div.className = "rotated";
}
break;
}
default: {
// any other case
}
}
}
Solution 2
Try this:
HTML
<div class="cardContainer">
<div class="card block">Click Here</div>
<div class="card block">Click Here</div>
<div class="card block">Click Here</div>
</div>
JavaScript
var cards = document.querySelectorAll(".card");
for (var i = 0; i < cards.length; i++) {
var card = cards[i];
card.onclick = function () {
if (this.classList.contains("block")) {
this.classList.add("rotated");
this.classList.remove("block");
}
else {
this.classList.add("block");
this.classList.remove("rotated");
}
};
}
Here is the Demo
Compatibility table for support of querySelector/querySelectorAll: Can I Use
user2163224
Updated on June 14, 2022Comments
-
user2163224 about 2 years
I checked out some other posts on here but still couldn't get this issue to work. I have several elements in my html with the class cardContainer:
<div class="cardContainer"> <div id="card2" class="block" onclick="changeClass()"> </div> </div> <div class="cardContainer"> <div id="card3" class="block" onclick="changeClass()"> </div> </div>
For each onClick event I would like to call this JS function:
<script type="text/javascript"> function changeClass(){ if(document.getElementById("card2").className == "block") document.getElementById("card2").className += " rotated"; else document.getElementById("card2").className = "block"; } </script>
What I would like to do is include the card3 id, so it fires the same function on click. How would I be able to combine the ids "card2" and "card3" in the javascript so the function works?
I get that if I use getElementById, I can only get one and not multiple ids/classes, but I tried using getElementsByClassName for example without success. Also looked at other posts but couldn't get this to work based on the suggestions... I am new to Javascript and not quite sure on how to approach this.
Thanks for your help!