How to create an event for multiple elements?

0

Function:

document.getElementsById("nome").onblur = function(){
//algum código aqui
}

What I do not like is:

<input type="text" onblur="nomedafuncao(this)">
    
asked by anonymous 31.07.2017 / 21:08

1 answer

1

Do something to select all the elements you want, then add the event listener to them.

In the example, I select all inputs and add the onblur event.

var elementos = document.querySelectorAll('input');
for(let el of elementos) {
  el.onblur = function(){
    console.log('yay');
  }
}
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
    
31.07.2017 / 21:13