Is there a pure Javascript way to apply one function to multiple element’s events?

I want to bind a single function to multiple events using pure Javascript.

In jQuery I would use:

$('.className').click(function(e){ //do stuff });

So using pure JS I tried:

document.getElementsByClassName('className').onclick = function(e){ //do stuff };

Which doesn’t work, because getElementsByClassName returns an array, not a DOM object.

I can loop through the array, but this seems overly verbose and like it shouldn’t be necessary:

var topBars = document.getElementsByClassName(‘className’); for(var i = 0; i < topBars.length; i++){ topBars[i].onclick = function(e){ //do stuff }; }

Is there a standard way to accomplish this with pure Javascript?


solution

You could add the event handler to the parent element, and then determine whether one of the children elements with the desired classname is clicked:

var parent = document.getElementById('parent');
parent.addEventListener('click', function (e) {
  if ((' ' + e.target.className + ' ').indexOf(' item ') !== -1) {
    // add logic here
    console.log(e.target);
  }
});

Example Here

or…

var parent = document.getElementById('parent');
parent.addEventListener('click', function (e) {
  Array.prototype.forEach.call(parent.querySelectorAll('.item'), function (el) {
    if (el === e.target) {
        // add logic here
        console.log(e.target);
    }
  });
});

Example Here


The above snippets will only work when you are clicking on the element with the specified class. In other words, it won’t work if you click on that given element’s child. To work around that, you could use the following:

var parent = document.getElementById('parent');
parent.addEventListener('click', function (e) {
var target = e.target; // Clicked element
while (target && target.parentNode !== parent) {
    target = target.parentNode; // If the clicked element isn't a direct child
    if (!target) { return; } // If element doesn't exist
  }
  if ((' ' + target.className + ' ').indexOf(' item ') !== -1){
    // add logic here
    console.log(target);
  }
});

Alternative Example

var parent = document.getElementById('parent');
parent.addEventListener('click', function (e) {
  var target = e.target; // Clicked element
  while (target && target.parentNode !== parent) {
    target = target.parentNode; // If the clicked element isn't a direct child
    if (!target) { return; } // If element doesn't exist
  }
  Array.prototype.forEach.call(parent.querySelectorAll('.item'), function (el) {
    if (el === target) {
        // add logic here
        console.log(target);
    }
  });
});

Example Here