Get element from which onclick function is called
Four options:
Pass
this
into the function.<button onclick="test(this)">Button 1</button>
and then use that argument in the function.
Hook up the handlers with
addEventListener
or jQuery'son
, and then usethis
within the handler.var buttons = document.querySelectorAll("selector-for-the-buttons"); Array.prototype.forEach.call(buttons, function(btn) { btn.addEventListener("click", handler, false); }); function handler() { // Use `this` here }
jQuery version:
$("selector-for-the-buttons").on("click", function() { // Use `this` here });
Hook up a single handler on a container these buttons are in, and use the
target
property of the event object to determine which was clicked (but note that if you use other elements withinbutton
, you'll need to loop up to thebutton
first).document.querySelector("selector-for-the-container").addEventListener("click", function(e) { // Use `e.target` here }, false);
jQuery version that handles the possibility of nested elements within the
button
for you:$("selector-for-the-container").on("click", "button", function() { // Use `this` here (note this is different from the DOM version above) });
function test(button)
{
var button_name = button.getAttribute('name');
console.log("Im button "+ button_name);
}
<button onclick="test(this)" name="button1">Button 1</button>
<button onclick="test(this)" name="button2">Button 2</button>
<button onclick="test(this)" name="button3">Button 3</button>
I came across an other extremely simple way to do it in Vanilla JS so I post it here for reference:
function whoami () {
var caller = event.target;
alert("I'm " + caller.textContent);
}
<button onclick="whoami()">Button 1</button>
<button onclick="whoami()">Button 2</button>
<button onclick="whoami()">Button 3</button>
I'm not sure about the browser support for it but it works at least on Safari, Firefox and Blink based browsers.
Pass the this
reference to the function, then read textContent
property the text content of the node.
HTML
<button onclick="test(this)">Button 1</button>
Script
function test(clickedElement){
var button_name = clickedElement.textContent;
}
Fiddle