I've been trying to change the width of a div with a set.interval animation. It works perfectly fine with getELementByID, but it won't work with getElementsByClassName.
The code is the following:
var loadingBar = 200;
function animationBarOne(){
document.getElementsByClassName("loading-bar").style.width=(loadingBar+"px");
loadingBar++;
if(loadingBar === 900){
clearInterval(intervalId);
}
}
var intervalId = setInterval(animationBarOne,1);
I'm getting "can't set property width of undefined". As I said it works perfectly with ID, but giving I have like 10 bars to animate I rather use class name so its cleaner.
Thanks in advance.
document.getElementsByClassName()
returns an array of elements. You need to loop through the array to modify each one in the list:
var loadingBar = 200;
function animationBarOne(){
var elements = document.getElementsByClassName("loading-bar");
for (var i = 0; i < elements.length; i++) {
elements[i].style.width=(loadingBar+"px");
}
loadingBar++;
if(loadingBar === 900){
clearInterval(intervalId);
}
}
var intervalId = setInterval(animationBarOne,1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With