I want to add mouseover
event to every link with linkLink
class with JS.
Console gives an error - Cannot read property style of undefined
.
Whenever I set index manualy like - l[0].addEventListener(...)
it
works fine, but not with variable i
. Any help?
var l = document.getElementsByClassName('linkLink');
for (var i = 0; i < l.length; i++) {
l[i].addEventListener("mouseover", function() { l[i].style.backgroundColor = "black"; });
if ((i % 2) === 0) l[i].style.color = "crimson";
else l[i].style.color = "gold";
}
<a class="linkLink" href="#">link I</a><br>
<a class="linkLink" href="#">link II</a><br>
<a class="linkLink" href="#">link III</a><br>