Skip to content Skip to sidebar Skip to footer

Event For Multiple Elements With The Same Class Name

I have the following code: var abbrs = document.getElementsByClassName('hover'); abbrs.onmouseover=function() { console.log(this); }; It should trigger when I hover over an e

Solution 1:

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]);
}

Solution 2:

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() {...});

Solution 3:

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);
        }
    }

Post a Comment for "Event For Multiple Elements With The Same Class Name"