Change the classname of multiple elements of a class

128 views Asked by At

I have multiple divs with the classnames of "card player1card". If I were to click on any element with the class "player1card", I want its class to change and for it to run the functions listed below.

So if I were to click the 5th element with the class "card player1card recruitbuilder", the class of the 5th element should change to "card player1card recruitmerchant" or any other random classname allocated from the array.

The current error that it gives me is "Uncaught TypeError: Cannot set property 'className' of undefined"

NOTE: All variables have been defined prior, so no missing variables or anything.

var p1card = document.getElementsByClassName("player1card");
var w;
var allocatedcard;

for (w = 0; w < p1card.length; w++) {
    p1card[w].onclick = function (){
        p1card[w].className = "card player1card";
        var allocatedcard = Math.floor(Math.random() * cardsnames.length);
        p1card[w].className += " " + cardsnames[allocatedcard];
        updateimages(); 
    }
}
1

There are 1 answers

4
Robby Cornelissen On BEST ANSWER

Use this.className instead of p1card[w].className in your click handler.