How to addEventListener to multiple elements in a single line

Well, if you have an array with the elements you could do:

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

elementsArray.forEach(function(elem) {
    elem.addEventListener("input", function() {
        //this function does stuff
    });
});

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 :

document.addEventListener('click', function(e){
  if(e.target.tagName=="BUTTON"){
   alert('BUTTON CLICKED');
  }
})

If you don't want to have a separate elementsArray variable defined you could just call forEach from an unnamed array with the two elements.

[ Element1, Element2 ].forEach(function(element) {
   element.addEventListener("input", function() {
      this function does stuff
   });
});

Tags:

Javascript

Dom