Skip to content
Advertisement

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?

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

Advertisement

Answer

This should work. getElementsByClassName returns an Array-like object (see below) of the elements matching the criteria.

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

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

for (var i = 0; i < elements.length; i++) {
    elements[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(elements).forEach(function(element) {
      element.addEventListener('click', myFunction);
    });

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


Details on getElementsByClassName

getElementsByClassName doesn’t return an array, but a HTMLCollection in most, or a NodeList in some browsers (Mozilla ref). Both of these types are Array-Like, (meaning that they have a length property and the objects can be accessed via their index), but are not strictly an Array or inherited from an Array (meaning other methods that can be performed on an Array cannot be performed on these types).

Thanks to user @Nemo for pointing this out and having me dig in to fully understand.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement