logo
post image

Add Event to Multiple Elements By Class in Javascript

Events can be added to multiple elements selected by class by looping through the list of elements using forEach and registering event for each element individually.

Selector functions like document.querySelectorAll() or document.getElementsByClassName() return a collection of elements. In such cases forEach can be used to loop through the collection.

document.querySelectorAll(".tree").forEach(function(element) {
	element.addEventListener('click', function() {
		// event handler code
	});
});
document.getElementsByClassName(".page").forEach(function(element) {
	element.addEventListener('click', function() {
		// event handler code
	});
});

The best part of using a forEach loop is that there is no need to declare extra variables, like in the case of a normal for or for .. of loop.

// iterator variable "i" is required if using for loop
for(let i=0; i<document.querySelectorAll(".element").length; i++) {
	document.querySelectorAll(".element")[i].addEventListener('click', function() {
		// event handler code
	});
}