Stephen Smith Stephen Smith - 1 year ago 64
Javascript Question

How do I get the element that an event handler was attached to from inside the handler?

Typically when attaching an event handler to an element, you can access the element using the .target member of the first argument passed into the handler function like so:

button.on('click', function(e) {

This would return the button element.

The issue I am trying to understand is that when you have an element inside the one with the event handler, the target of the event is the inner element instead of the one that had the handler attached to it. This is an issue when my event handler needs to access data attached to the outer element.

<div class="outer" data-tag="i-need-this-data">
<b>Click Me</b>

With this markup, attaching an event to
and clicking on
Click Me
will result in being the
instead of the
. This is problematic as I must use workarounds like checking for the outer class, climbing up the DOM until I see
, then accessing the data that way. An example of this behavior can be seen in this JSFiddle:

The first example in the JSFiddle shows the undesired behavior, clicking on the inner square causes to be the inner square. The second example shows an implementation of my workaround.

Is there a cleaner way to get the element that the handler was attached to from inside the handler instead of the element that was clicked?

Answer Source

Just use the element you're already using in the loop. this is also set to the current element:

$$('.two').each(function(element) {
    element.on('click', function(e) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download