How to get the id of the onclick that was executed

Asked

Viewed 1,163 times

1

Well here’s the thing, I have a button that has the following structure:

<button id="goncalo" onclick="ativafuncao()">Goncalo</button>

How do I make for the function activating(), know that it was the id "Goncalo" that called her?

I hope you made me understand.

Thank you.

3 answers

4


It is possible to pass this in function call and capture element id in function.

function ativafuncao(obj){
  console.log(obj.id);
}
<button id="teste" onclick="ativafuncao(this)">Clicar</button>

3

You can use this.id as a parameter of the function enabled:

<button id="goncalo" onclick="ativafuncao(this.id)">Goncalo</button>

See the code working here

I hope I’ve helped ;)

2

You can also use the event variable this way:

HTML

<button id="meu-botao">Clica</button>

Javascript

var meuBotao = document.getElementById('meu-botao');
meuBotao.addEventListener('click', function(event) {
  console.log(event.target.id);
});

Target refers to the button that was clicked.

Browser other questions tagged

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