5

I am currently using addEventListener on a select:

<select> <option value="Apple">Mac</option> <option value="Microsoft">Windows</option> </select> document.querySelector("select").addEventListener("change",function(ev){ //do something here... }, false); 

But I can't figure out how to get the original element from event.

PS: I don't want to do this:

<select onchange="func(event,this)"> 

This will only mess up the HTML...

0

1 Answer 1

3

The element that caused the event is automatically assigned to this in the event handler. It's also in the event data structure which is passed to the addEventListener() callback and in your example is ev.target.

document.querySelector("select").addEventListener("change",function(ev){ //do something here... // you can use the value of this to access the object that // is responding to the event // you can also look in the event data structure for // other items like ev.target }, false); 

You can see all the members of the event object here.

Sign up to request clarification or add additional context in comments.

2 Comments

There's a difference between this and ev.target. 'this' is the topmost element which had the event attached, ev.target is the innermost element that received the event.
@MaciejKrawczyk - Yes, if the event bubbles, ev.target and this will vary. At the source of the event, they are the same.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.