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

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)



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

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

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

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.

EDIT : Correction

getElementsByClassName doesnt 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.


* This was edited to allow for children of the target class to trigger the events. See bottom of the answer for details. *

An alternative answer to add an event listener to a class where items are frequently being added and removed. This is inspired by jQuery's on function where you can pass in a selector for a child element that the event is listening on.

var base = document.querySelector('#base'); // the container for the variable content
var selector = '.card'; // any css selector for children

base.addEventListener('click', function(event) {
  // find the closest parent of the event target that
  // matches the selector
  var closest =;
  if (closest && base.contains(closest)) {
    // handle class event


This will listen for clicks on children of the base element and if the target of a click has a parent matching the selector, the class event will be handled. You can add and remove elements as you like without having to add more click listeners to the individual elements. This will catch them all even for elements added after this listener was added, just like the jQuery functionality (which I imagine is somewhat similar under the hood).

This depends on the events propagating, so if you stopPropagation on the event somewhere else, this may not work. Also, the closest function has some compatibility issues with IE apparently (what doesn't?).

This could be made into a function if you need to do this type of action listening repeatedly, like

function addChildEventListener(base, eventName, selector, handler) {
  base.addEventListener(eventName, function(event) {
    var closest =;
    if (closest && base.contains(closest)) {
      // passes the event to the handler and sets `this`
      // in the handler as the closest parent matching the
      // selector from the target element of the event, event);

EDIT: This post originally used the matches function for DOM elements on the event target, but this restricted the targets of events to the direct class only. It has been updated to use the closest function instead, allowing for events on children of the desired class to trigger the events as well. The original matches code can be found at the original fiddle:


You can use the code below:

document.body.addEventListener('click', function (evt) {
    if ( === 'databox') {
}, false);

With modern JavaScript it can be done like this:

const divs = document.querySelectorAll('.a');

divs.forEach(el => el.addEventListener('click', event => {
<!DOCTYPE html>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
    .a {
      height: 33px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      cursor: pointer;
    .b {
      height: 50px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
  <div class="a a-1">1</div>
  <div class="b">2</div>
  <div class="a a-2">11</div>

  1. Gets all elements by class name
  2. Loops over all elements with using forEach
  3. Attach an event listener on each element
  4. Uses to retrieve more information for specific element


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.