0

I'm trying to get my class to toggle but it won't work. I get an error message saying "Uncaught TypeError: Cannot read property 'toggle' of undefined".

This is my Javascript:

var sound = document.getElementById("sound");
var two = document.getElementsByClassName("two");
var twoanimated = document.getElementsByClassName("twoanimated");

function animatie () {
    two.classList.toggle("twoanimated");
}

sound.addEventListener("click", animatie);

What am I doing wrong?

H0ndman2
  • 41
  • 2
  • 8

1 Answers1

1

The reason is here:

var two = document.getElementsByClassName("two");

The two is a HTMLCollection and not a single element. So you need to do:

two[0].classList.toggle("twoanimated");

The above code works if there's only one single element for the class name twoanimated. If there are multiple, please use a counter loop something like this:

function animatie () {
  for (var i = 0; i < two.length; i++) {
    two[i].classList.toggle("twoanimated");
  }
}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252