Bind event to multiple elements without looping (vanilla JS)

Viewed 3628

I'm trying to achieve the equivalent of:

$('div').on('click', function() {
    // Do something
});

But without jQuery. My initial thought was to use a for loop to iterate over all elements in the set, but my guess is there's a better way of achieving this without using a loop (some native method?).

var elems = document.getElementsByTagName('div');

function someEvent() { // Generic function to test against
    alert('event fired');
}

for (var i=0, j = elems.length; i < j; i += 1) {
    elems[i].addEventListener("click", someEvent);
}

Is there a more elegant way of doing this without the inclusion of a library?

1 Answers
Related