30secondstosam 30secondstosam - 3 months ago 24
Javascript Question

Javascript click event listener on class

I'm currently trying to write some JavaScript to get the attribute of the class that has been clicked. I know that to do this the correct way, I should use an event listener.
My code is as follows:

var classname = document.getElementsByClassName("classname");

var myFunction = function() {
var attribute = this.getAttribute("data-myattribute");
alert(attribute);
};

classname.addEventListener('click', myFunction(), false);


I was expecting to get an alert box every time I clicked on one of the classes to tell me the attribute but unfortunately this does not work. Can anyone help please?

(Note - I can quite easily do this in
jQuery
but I would NOT like to use it
)

Answer

This should work. getElementsByClassName returns an array of the elements matching the criteria.

var classname = document.getElementsByClassName("classname");

var myFunction = function() {
    var attribute = this.getAttribute("data-myattribute");
    alert(attribute);
};

for (var i = 0; i < classname.length; i++) {
    classname[i].addEventListener('click', myFunction, false);
}

jQuery does the looping part for you, which you need to do in plain JavaScript.

If you have ES6 support you can replace your last line with:

    Array.from(classname).forEach(function(element) {
      element.addEventListener('click', myFunction);
    });

Note: Older browsers (like IE6, IE7, IE8) donĀ“t support getElementsByClassName and so they return undefined.