EdwardBlack EdwardBlack - 1 month ago 5
Javascript Question

Get element from which onclick function is called

I have a button with a onclick attribute which is pointing to the function

test()
.

<button onclick="test()">Button 1</button>
<button onclick="test()">Button 2</button>
<button onclick="test()">Button 3</button>


Function test():

function test()
{
var button_name = this.html;
console.log("Im button "+ button_name);
}


How can I get informations about the clicked button?
e.g. How can i read the html?

jsfiddle: https://jsfiddle.net/c2sc9j9e/

Answer

Four options:

  1. Pass this into the function.

    <button onclick="test(this)">Button 1</button>
    

    and then use that argument in the function.

  2. Hook up the handlers with addEventListener or jQuery's on, and then use this 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
    });
    
  3. 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 within button, you'll need to loop up to the button 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)
    });