Dymond
Dymond

Reputation: 2277

element.className wont change my class name in for-loop JavaScript only

I'm struggling with this function, but I cant seem to get it work when its inside a for loop.

When its not inside the loop it changes my className.

Any tips ?

This is when the function works.

 function addDiceEvent() {
           var diceClass = document.getElementsByClassName("dice")[0];
           diceClass.className = "dice-two";

           }

But since there is alot of classes with the name dice i need to change them with an loop.

with this code, there is no magic.

function addDiceEvent() {
       var diceClass = document.getElementsByClassName("dice");
                 for(var i = 0; i<diceClass.length; i++){
         diceClass.className = "dice-two";              

       }
    }

Upvotes: 0

Views: 440

Answers (1)

Andrey
Andrey

Reputation: 60065

Change that to diceClass[i].className = "dice-two"; In first piece diceClass was one particular element, and in second one it is the whole array of elements.

Also I highly recommend considering using jQuery, it would be a one-liner with it.

Upvotes: 3

Related Questions