0

I am getting a cannot read property style of undefined error, and I am not sure why it is returning undefined. I am attempting to have my elements change color on mouseover. The code I am using is:

var icons = document.getElementsByClassName('icon');
for ( i = 0; i < icons.length; i++) {
    console.log(icons.length);
    icons[i].addEventListener('mouseover', function() {
        console.log(icons[i]);
        icons[i].style.color = "#00FF00";
    });
};

EDIT: I was able to get it to work by doing the following:

var icon = document.getElementsByClassName('icon');

function getValue(i) {
    return (i);
}

for (var i = 0; i < icon.length; i++) {
    icon[i] = getValue(i);
    icon[i].addEventListener('mouseover', function() {
        this.style.backgroundColor = "#00FF00";
    });
    icon[i].addEventListener('mouseout', function() {
        this.style.backgroundColor = "white";
    });
}

0 Answers0