Call onClick Function On Multiple Elements

user2163224 picture user2163224 · Jun 19, 2014 · Viewed 14.8k times · Source

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!

Answer

super picture super · Jun 19, 2014

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