James G.
James G.

Reputation: 2904

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?

Upvotes: 5

Views: 2269

Answers (3)

Mouser
Mouser

Reputation: 13304

var elems = document.querySelectorAll('.className');
var values = Array.prototype.map.call(elems, function(obj) {
    return obj.onclick = function(e){ //do stuff };
});

This (adapted example from MDN) is how you could do it without a traditional loop.

Upvotes: -1

Josh Crozier
Josh Crozier

Reputation: 240948

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

Upvotes: 10

RobG
RobG

Reputation: 147413

As a hack, where the DOM is implemented using a prototype inheritance model (most browsers but not all), you can add an iterator to the NodeList constructor:

if (NodeList && NodeList.prototype && !NodeList.prototype.forEach) {
  NodeList.prototype.forEach = function(callback, thisArg) {
    Array.prototype.forEach.call(this, callback, thisArg)
  }
} 

Then:

document.getElementsByClassName('item').forEach(function(el){
  el.addEventListener('click', someFn, false);
})

or

document.querySelectorAll('.item').forEach(function(el){
  el.addEventListener('click', someFn, false);
})

Of course you shouldn't do this in production on the web (don't mess with host objects and all that), but wouldn't it be nice if it was OK? Or iterators were added to DOM lists and collections?

Upvotes: 1

Related Questions