What is wrong with this code? [JavaScript] | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is wrong with this code? [JavaScript]

Everything works fine with id's, but I need it for more than 1 element. The point is to make a button that changes properties when user hovers cursor over it. I have tried to do mouseover[0],style[...] but it don't work either. function mouseover() { var mouseover = document.getElementsByClassName("other"); mouseover.style.backgroundColor = "#FF0000"; mouseover.style.border = " 3px solid rgba(130,0,0,1"; mouseover.style.boxShadow = " 0px 0px 60px rgba(130,0,0,1)"; mouseover.style.fontWeight = " bold"; } function mouseout() { var mouseout = document.getElementsByClassName("other"); mouseout.style.backgroundColor = "#820000"; mouseout.style.border = " 3px solid rgba(130,0,0,0)"; mouseout.style.boxShadow = " 0px 0px 30px rgba(130,0,0,0)"; mouseout.style.fontWeight = " normal"; }

1st Apr 2017, 6:24 PM
Kuba Nawieśniak
Kuba Nawieśniak - avatar
3 Answers
+ 14
Hm. Why do you use JavaScript for that? Try to use CSS: .btn { background-color: #820000; ... } .btn:hover { background-color: #FF0000; ... } Anyway, Mario's answer is great. It should work, because .getElementsByClassName method returns a list.
2nd Apr 2017, 4:08 PM
K137(){/**/};
K137(){/**/}; - avatar
+ 5
for (var i = 0, p = document.getElementsByClassName("other"); i < p.length; i++) { p.style.backgroundColor = "#FF0000"; .... }
1st Apr 2017, 6:37 PM
Mario L.
Mario L. - avatar
+ 2
document.getElementsByClassName returns an array-like object, so in order to access each element of a class, you should use a loop. Mario is almost right, he's missing the p's index (it should be for(...){ p[i].style... } ), so you change the style of each element instead of the array-like object.
1st Apr 2017, 10:47 PM
Luca Garrera