Raul Leaño Martinet
Raul Leaño Martinet

Reputation: 2113

get the element that triggers a javascript function

i want to know if i can access the element that triggers a function in javascript. i know... it's kinda hard to understand but maybe if you see the following code you'll get what i try to explain:

CODE HTML:

<a href="javascript:myFunction(this)">link</a>

CODE JS:

function myFunction(linkElement) {
   console.log(linkElement);
}

Obviously that doesn't work, but the idea is that i would like to have access to the element that triggers (or calls) the function so that the console.log would give me the 'a' element.

I know you can use an ID and send the ID to the function and easily recover the element, but it would be much nicer if i can use something more relative like the 'this' statement.

Upvotes: 3

Views: 6951

Answers (2)

jaybro
jaybro

Reputation: 1543

How about event.target? https://developer.mozilla.org/en-US/docs/Web/API/Event/target

The target property of the Event interface is a reference to the object that dispatched the event.

function myFunction() {
    console.log(event.target);
}

Upvotes: 2

Luca Matteis
Luca Matteis

Reputation: 29267

Change this

<a href="javascript:myFunction(this)">link</a>

to this

<a href="#" onclick="myFunction(this); return false;">link</a>

Upvotes: 8

Related Questions