-2

Why is mouse on hover in javascript is not working with classes but works on ids?

for example,

 window.onload = function() {
    var myIcon = document.getElementsByClassName('myIcon'); //does not work
    myIcon.onmouseover = function() {
        // do something
        return false;
    };
};   

but

window.onload = function() {

    var myIcon = document.getElementsByID('myIcon'); //works 

    myIcon.onmouseover = function() {
        // do something
        return false;
    };
};   
Turnip
  • 35,836
  • 15
  • 89
  • 111
djangog
  • 47
  • 1
  • 11
  • 1
    Possible duplicate of [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](http://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – Adam Buchanan Smith Sep 01 '16 at 22:55

1 Answers1

2

You've got two variables of the same name, which is redeclaring and reassigning myIcon. Also, getElementsByID is not a function, getElementById or getElementsById is. getElementsById then returns a NodeList with an 'array' of elements. Finally, getElementsByClassName also returns a NodeList. Both are array-like so you must treat it like so.

Here's an example on JSFiddle, note that getElementsByClassName in the example only applies to the first element with the class myIcon. You can use a for loop to loop through all elements and change their listeners.

var myIcon_class = document.getElementsByClassName('myIcon')[0]; //note, gets first element
var myIcon = document.getElementById('myIcon')
    
myIcon.onmouseover = function() {
    alert("hovered on ID!");
    return false;
};
    
myIcon_class.onmouseover = function() {
 alert("hovered on class!");
    return false;
}; 
<span id="myIcon">Id span!</span>
<span class="myIcon">Class span!</span>
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
  • oops sorry, I am actually using one myIcon variable it was just for illustration, I'm editing my question. – djangog Sep 01 '16 at 22:54