How to create an event for multiple elements?

Asked

Viewed 85 times

0

Function:

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

note that in the above code I can only run for a single element, I would like to explicitly type 3 specific events, or for all type of an element, example with Document.getelementsbytagname

What I wouldn’t like is:

<input type="text" onblur="nomedafuncao(this)">

1 answer

1


Do something to select all the elements you want and then add the Event Listener to them.

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

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">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.