Why does getElementsByClassName return undefined? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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)"; } }

28th Feb 2020, 5:40 AM
Marie Johnson
5 Answers
+ 8
window.onload should be a function and NOT a function call Change to this: window.onload= myStuff;
28th Feb 2020, 5:54 AM
Burey
Burey - avatar
+ 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
28th Feb 2020, 5:43 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
0
https://code.sololearn.com/Wtt211CWcukT/?ref=app
28th Feb 2020, 5:51 AM
Marie Johnson
0
Thank you!
28th Feb 2020, 5:55 AM
Marie Johnson
0
It seems that my longer code was messing up because I assigned multiple classes to the same element.
28th Feb 2020, 6:18 AM
Marie Johnson