why mouse on hover in javascript not working classes works on ids?
for example,
window.onload = function() { var myicon = document.getelementsbyclassname('myicon'); //does not work myicon.onmouseover = function() { // return false; }; }; window.onload = function() { var myicon = document.getelementsbyid('myicon'); //works myicon.onmouseover = function() { // return false; }; };
you've got 2 variables of same name, redeclaring , reassigning myicon
. also, getelementsbyid
not function, getelementbyid
or getelementsbyid
is. getelementsbyid
returns nodelist 'array' of elements. finally, getelementsbyclassname
returns nodelist. both array-like must treat so.
here's example on jsfiddle, note getelementsbyclassname
in example applies first element class myicon
. can use loop loop through elements , change 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>
Comments
Post a Comment