Member-only story

JavaScript — How to add an eventListener to multiple elements

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

Explanation: Event Bubbling is the important concept in javascript, so if you can add event on DOM directly, you can save some lines of code, no need for looping.

Become a member on Medium!

Amazon Links to “Must-Haves” as a WFH Software Engineer 🙂💻

24-inch budget-friendly monitor, Portable monitor, Laptop stand, Waterproof desk mat, Keyboard cleaning gel, Six-outlet wall charger and surge protector,, Wi-Fi extender, Blue-light–blocking glasses, Memory foam gel pad, Foam footrest

Courses to learn more about datastructures/algorithms ✍️

Stanford, Duke, UCSD

Courses to learn more about databases 👓

DB Foundations, Data Scientists specialization

Courses to learn more about React 🧢

Full-Stack WebDev, Front-End WebDev with React, IBM Full Stack

--

--

No responses yet