SHiRKiT
SHiRKiT

Reputation: 1022

How to get registred element for event listener?

I have a page which has a bunch of nested elements.

div - div - - div - - - a - - - - div - - - - - span - - - - - - img

This pattern and variations of it repeats throughout the page.

I'm currently registering for the a element doing

document.querySelectorAll('.click-aware a').addEventListener('click', myListener);

function myListener(evt) {
  // some logic function goes here
}

The thing is, the evt object does not contain a reference to the a element.

evt.target points to the innermost element (in this example the img), and both srcElement and toElement points to it as well.

How do I get the a element without having to traverse the evt.path upwards until I hit the a?

No jQuery allowed

I'm asking this because sometimes the listener is not attached to the a element.

TLDR: How do I get the element that the event listener was registred to?

Upvotes: 1

Views: 67

Answers (1)

Tiago Coelho
Tiago Coelho

Reputation: 5101

You can use the this keyword to get the reference to the element that owns the handler, or the event.currentTarget property (https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget)

Event.currentTarget Identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to event.target which identifies the element on which the event occurred.

the event.currentTarget is a better option, because if the handler is defined using an arrow function (es6) instead of a regular old function, then the this will refer to the context where the handler function is defined instead.

Upvotes: 2

Related Questions