Alex Rivera | Logout

How to use "this" reference of the element calling the function?

Asked 2012-09-17T09:24:45.457
18

For example I want a function that is used by many elements to get the attributes of the calling element.

function example(){
    var name = //name of the calling element "$(this).attr('name')"
}
<button name="somename1" onclick="example()">Button1</button>
<button name="somename2" onclick="example()">Button2</button>

so if the button named 'somename1' calls the function, the variable 'name' will be assigned to 'somename1' and so if 'somename2' called it, it will be assigned to 'somename2'

Edit
Report

1 Answer

29

Use the keyword this, like so:

function exampleFunction(exampleElement) {
    var name = exampleElement.name;
}

<button name="somename1" onclick="exampleFunction(this)">Button1</button>
<button name="somename2" onclick="exampleFunction(this)">Button2</button>

But if you use jquery, you could do

$('button').click(function() {
  var name = $(this).attr('name');
});

Without the onclick attribute.

answered 2012-09-17T09:28:15.777

Your Answer