There are a few options for how to do this, and each behaves differently.
Option 1
Set onclick="btn(this)"
on the button. This always passes the button itself as the argument. The other options pass an event as opposed to the element itself.
function btn(elem) {
var theTarget = elem;
console.log(theTarget.id);
}
<p>
Option 1:
<button id="the-button" onclick="btn(this)">
btn(this)
<span id="the-span" style="border: 1px solid red">This is a span</span>
</button>
</p>
Option 2
Set onclick="btn(event)"
on the button. This passes the event, and event.target
will be element that is clicked. For example, an event referencing a span
inside the button would be passed if it was clicked.
function btn(evt) {
var theTarget = evt.target;
console.log(theTarget.id);
}
<p>
Option 2:
<button id="the-button" onclick="btn(event)">
btn(event)
<span id="the-span" style="border: 1px solid red">This is a span</span>
</button>
</p>
</p>
Option 3
Set an id
attribute for the button. Then bind an event handler to the button with JavaScript. This behaves like option 2 with respect to the way child elements are referenced by the event.
function btn(evt) {
var theTarget = evt.target;
console.log(theTarget.id);
}
document.getElementById('the-button').onclick = btn;
<p>
Option 3:
<button id="the-button">
binding
<span id="the-span" style="border: 1px solid red">This is a span</span>
</button>
</p>
Here is a snippet with all three options in one program:
function btn(evt) {
var theTarget = evt.target || evt;
console.log(theTarget.id);
}
document.getElementById('third-button').onclick = btn;
<p>
Option 1:
<button id="first-button" onclick="btn(this)">
btn(this)
<span id="first-button-SPAN" style="border: 1px solid red">This is a span</span>
</button>
</p>
<p>
Option 2:
<button id="second-button" onclick="btn(event)">
btn(event)
<span id="second-button-SPAN" style="border: 1px solid red">This is a span</span>
</button>
</p>
<p>
Option 3:
<button id="third-button">
binding
<span id="third-button-SPAN" style="border: 1px solid red">This is a span</span>
</button>
</p>