JavaScript — How to add an eventListener to multiple elements

All About Code
1 min readOct 28, 2022

Method #1: Use a for loop through all input elements

let elementsArray = document.querySelectorAll("input");

elementsArray.forEach(function(elem) {
elem.addEventListener("input", function() {
console.log("CHANGE!");
});
});

Method #2: Listen to the ‘document’

document.addEventListener('click', function(e){
if(e.target.tagName=="BUTTON"){
console.log("CHANGE!");
}
})

--

--