2

I have the following code:

var abbrs = document.getElementsByClassName("hover");
abbrs.onmouseover=function() {
     console.log(this);
};

It should trigger when I hover over an element with the class "hover", but it is not working. What am i doing wrong?

Cornwell
  • 3,304
  • 7
  • 51
  • 84

3 Answers3

3

As its name suggests document.getElementsByClassName returns a list of elements, with the hover as their className, so you can do it like:

var i=0,
  len = abbrs.length,
  abbrs = document.getElementsByClassName("hover");

for( ; i < len ; i++){
    abbrs[i].addEventListener("mouseover", function(event){
        //...
    });
}

Although it answers the question but in terms of a better coding practice we better avoid from creating functions in loops. So the better practice could be something like this:

var i=0,
  len = abbrs.length,
  abbrs = document.getElementsByClassName("hover");

fnction addEvent(abbr){
    abbr.addEventListener("mouseover", function(event){
        //...
    });
}

for( ; i < len ; i++){
    addEvent(abbrs[i]);
}
Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35
0

document.getElementsByClassName returns either a NodeList or HTMLCollection depending on your current browser and version.

To add event listeners to all of the items in the "abbrs" collection/list you would need to do:

for(i=0; i< abbrs.length; i++) {
  abbrs[i].onmouseover=function() {...};
}

Alternately, using jQuery:

$(".hover").on("mouseover", function() {...});
Clayton Gulick
  • 9,755
  • 2
  • 36
  • 26
0

See the code below (I assume you are not using jquery)

    var abbrs = document.getElementsByClassName("hover");

    var index,l=abbrs.length;
    for (index = 0; index < l; ++index) {
        console.log(abbrs[index]);
        abbrs[index].onmouseover = function() {
            console.log(this);
        }
    }
csg
  • 2,047
  • 2
  • 22
  • 35