0

I have the following Javascript code:

setTimeout(function() {
  var el = document.getElementsByClassName('video');
  el.className += " hidden";
  // el[0].style.visibility = 'hidden'; 
}, 3000);

I wanted the script to add an class hidden to the video class. Wat is wrong about my code?

Your sincerely

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
  • As the method name suggests, the return value of [`.getElementsByClassName()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName) is a collection of elements. What you already know, based on the commented part in the code... – Andreas Jan 31 '17 at 19:11

1 Answers1

1

You are missing the iteration part. The method getElementsByClassName returns a NodeList of elements. So, you need to iterate over the NodeList

setTimeout(
function(){

var el = document.getElementsByClassName('video');

for(var element of el){
el.className += "hidden";
}

}
,3000);
Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41
  • 1
    [`for...in...`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...in_statement) is meant for objects and not arrays (or array-like objects) -> [Why is using “for…in” with array iteration a bad idea?](https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea) – Andreas Jan 31 '17 at 19:17
  • Thanks for the post. Try it out but it doesn't works well. I'm just an beginner @ Javascript. Because of de getElementsByClassName it makes automatic ly an array, because is checks all the classes right? Why does el.className[0]+= " hidden"; nog work? – Levi Nijveldt Jan 31 '17 at 19:19
  • @Andreas Yes, you are right, was writing some c# code, corrected the post to use `for of` loop. – Abhinav Galodha Jan 31 '17 at 19:20
  • @LeviNijveldt, you need to write it like `el[0].className = "hidden"` instead of `el.className[0] = " hidden"` – Abhinav Galodha Jan 31 '17 at 19:21
  • That was the answer i've been looking for. Thank Agalo. – Levi Nijveldt Jan 31 '17 at 19:35
  • @LeviNijveldt Glad it helped. – Abhinav Galodha Jan 31 '17 at 19:36