JavaScript — How to add an eventListener to multiple elements

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!");
}
})

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store