Skip to content Skip to sidebar Skip to footer

How Do You Assign An Event Handler To Multiple Elements In Javascript?

I know how to do so with jQuery, and I know how to do so with event delegation. But how do you do so in plain JavaScript? For example, how do you assign an event handler to a bunch

Solution 1:

Yes, you should loop through the collection and assign the handlers individually. jQuery also does this behind the scenes.

querySelectorAll returns a NodeList which is an array-like object.

For looping through the list, you can either use a for loop:

var list = document.querySelectorAll('li'),
    l = list.length,
    li;

for (var i = 0; i < l; i++) {
   li = list.item(i);
   // ...
} 

Or use the forEach method:

[].forEach.call(document.querySelectorAll('li'), function(li) {
    // ...
});

Post a Comment for "How Do You Assign An Event Handler To Multiple Elements In Javascript?"