0

getElementbyID works since IDs have to be unique and thus the function always returns exactly one element (or null if none was found). Got struck with the class name. How can i add the style.animation to the class name ?

function myFunction() {
  document.getElementsByClassName("myDIV").style.WebkitAnimation = "mynewmove 4s 2"; 
  document.getElementsByClassName("myDIV").style.animation = "mynewmove 4s 2";
}
.myDIV {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  -webkit-animation: mymove 1s infinite;
  /* Chrome, Safari, Opera */
  animation: mymove 1s infinite;
}


@-webkit-keyframes mymove {
  from {
    left: 0px;
  }
  to {
    left: 200px;
  }
}


@-webkit-keyframes mynewmove {
  from {
    top: 0px;
  }
  to {
    top: 200px;
  }
}
@keyframes mymove {
  from {
    left: 0px;
  }
  to {
    left: 200px;
  }
}
@keyframes mynewmove {
  from {
    top: 0px;
  }
  to {
    top: 200px;
  }
}
<button onclick="myFunction()">Try it</button>



<div class="myDIV"></div>
abu
  • 5
  • 5
  • possible duplicate of [What does getElementsByClassName return?](http://stackoverflow.com/questions/10693845/what-does-getelementsbyclassname-return) – light Jun 14 '15 at 14:58

1 Answers1

0

getElementsByClassName returns a HTMLCollection, therefore, you either need to access specific items([0]) or iterate over them

function myFunction() {
  document.getElementsByClassName("myDIV")[0].style.WebkitAnimation = "mynewmove 4s 2"; 
  document.getElementsByClassName("myDIV")[0].style.animation = "mynewmove 4s 2";
}
.myDIV {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  -webkit-animation: mymove 1s infinite;
  /* Chrome, Safari, Opera */
  animation: mymove 1s infinite;
}


@-webkit-keyframes mymove {
  from {
    left: 0px;
  }
  to {
    left: 200px;
  }
}


@-webkit-keyframes mynewmove {
  from {
    top: 0px;
  }
  to {
    top: 200px;
  }
}
@keyframes mymove {
  from {
    left: 0px;
  }
  to {
    left: 200px;
  }
}
@keyframes mynewmove {
  from {
    top: 0px;
  }
  to {
    top: 200px;
  }
}
<button onclick="myFunction()">Try it</button>



<div class="myDIV"></div>
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • Specifically, it returns a `HTMLCollection`, not a `NodeList`. – Oriol Jun 14 '15 at 14:26
  • @Oriol, did you know I had them mixed up in my mind! I even just went to the documentation to prove you wrong, but I proved myself wrong! :) Thanks for the correction – AmmarCSE Jun 14 '15 at 14:28
  • Yes, I always doubt too :) It doesn't help that previously it returned a `NodeList`, but the spec changed. – Oriol Jun 14 '15 at 14:30