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
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) {
// ...
});