1

I have a nested html structure that needs to change in a certain way when clicked. For that, i need the element that the event is bound to, not the element that is clicked

For example....

theDesiredElement.addEventListener('click', function() { ... i need 'theDesiredElement' here } , false); 

Getting event.target get's the clicked element, not the element that the event is bound to. Is there a way to do that?

5
  • Can you explain what higher level problem you're really trying to solve? If the event is not propagating, then this or event.target will be the element that the event occurred in and the event handler is attached to. Commented May 2, 2014 at 18:45
  • The element that the event is bound to and the element click isn't the same? Commented May 2, 2014 at 18:47
  • 3
    Use this jsfiddle.net/zLLyS Commented May 2, 2014 at 18:47
  • Yea, i just found that out 15 seconds after i posted the question. I found it on the MDN. Kill me and hide my grave. Commented May 2, 2014 at 18:50
  • @MarioLegenda congrats on finding the answer to your question on MDN, don't forget to select an answer to the question if any of the answers below match the solution you came up with. :) Commented May 2, 2014 at 19:19

3 Answers 3

1
theDesiredElement.addEventListener('click', function(event) { ... i need 'theDesiredElement' here theDesiredElement=event.target; } , false); 

Based on what you are looking, you may have to get the parent node of target;

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

Comments

0

The function that you pass in, as the bound function for processing the click event, should take the event triggered as a parameter to it, allowing you to get details like the target of the event.

E.g.

var el = document.getElementById("theDesiredElement"); el.addEventListener('click', function(/*DOMEvent*/ evt) { ... }, false); 

Hanging off of evt you should be able to find the element that was clicked--e.g. theDesiredElement, accessing it with:

var desired = evt.target; 

See the following jsfiddle: http://jsfiddle.net/BbZgW/

For more details about addEventListener, take a look at EventTarget.addEventListener on MDN.

Comments

0

The answer is using this inside the function bound to the event. It points to the desired element.

2 Comments

Or you could also use a closure and theDesiredElement inside of it.
when i used that, the element was undefined. using this is just fine but i have a hunch that browser support is not wide on that. I'll do some research on it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.