How to get the id of the onclick that was executed

1

Well, this is the following, I have a button that has the following structure:

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

How do I do the active function (), know that it was the id "goncalo" that called it?

I hope you've made me understand.

Thank you.

    
asked by anonymous 07.03.2017 / 00:19

3 answers

4

You can pass this on the function call and capture the element id in the function.

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

You can use this.id as a parameter of the activefunction () function as follows:

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

See the code working here

I hope I have helped;)

    
07.03.2017 / 00:33
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.

    
07.03.2017 / 01:13