0
Why does getElementsByClassName return undefined?
window.onload= myStuff(); function myStuff(){ var spoil =document.getElementsByClassName("spoilers"); for(var i=0; i<spoil.length;i++){ spoil[i].style.color="rgb(255,0,0)"; } }
5 Answers
+ 8
window.onload should be a function and NOT a function call
Change to this:
window.onload= myStuff;
+ 1
It's not possible to answer without watching the DOM content (HTML)
According to MDN and what I have tried in playground getElementByClassName always returns [HTMLCollection] not undefined.
Even if no elements with specified class are found then also it returns [HTMLCollection].
When no elements are found length of Collection will will be 0.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
0
https://code.sololearn.com/Wtt211CWcukT/?ref=app
0
Thank you!
0
It seems that my longer code was messing up because I assigned multiple classes to the same element.