View Full Version : reference to event target element parent

03-23-2012, 09:35 PM
I have a situation where an image tag is nested in an anchor tag set.
The anchor is assigned an id and is assigned a click/onclick event listener.
The anchor id corresponds to a list of objects in an array.

In practice, the image tag is receiving the event. The code does setAttribute in another elements img tag src attribute.

The image tag receiving the click event, (and passing it to the anchor tag)
is event.target. (or event.srcElement, in the case of I.E.)

My Question:
What I want to know is how to reference the event.target
parent element, the anchor tag elements Id attribute.

sample anchor/img tag set:
<a style="font-family:Arial, Helvetica, sans-serif;color:#cccccc" id="An 1" alt="An 1" href="javascript:"><img style="border:1px solid;border-color:#cccccc" src="WC_port/windows/img//an_1.jpg" width="100" height="131" /><br /><br />An 1</a>

I see the double slash in the img src path attribute. It is working as is
in test browser: Firefox ( so far)

This is in development stages. Later, I will assign the elements a css class

in my code, event.target.src has a usable value (src attribute of the img tag)
It does not have a usable value for event.target.id (id attribute of the anchor tag)

I am doing it this way so in the absence of javascript, the anchors href
attribute defaults to a non scripted value.

Thank you for time and attention

Old Pedant
03-23-2012, 10:39 PM

03-23-2012, 11:05 PM
Thanks for the reply.

It also occurred to me that I can assign the id to the image tag, so
the event is registered on the image tag directly. But this still useful
because in the absence of javascript I can assign the default href
value (via php processing). If javascript is functional, it can reassign
the parentNode href attribute value.


03-24-2012, 10:38 AM
You don't need anything on the tag itself to be able to reference it from JavaScript if it was the element that triggered the event currently being processed. The following code will return the tag regardless of which browser is being used since Internet Explorer stores the event differently and stores the element in srcElement instead of target (it also contains the code so that if it was a text node that triggered the event that it gets the parent tag so if the text in an <a> tag triggered the event a reference to the <a> tag is returned):

whichElement = function(e) {
var targ;
targ = (window.event) ? window.event.srcElement : e.target;
if (3===targ.nodeType) {
targ = targ.parentNode;
return targ;

With an <img> tag triggering the event you'd need to get the parentNode of the <img> in order to get to the <a>


03-24-2012, 11:36 AM
modern browsers (not IE, of course) also have the Event.currentTarget property.

Another possibility would be to get the current Element via this, unless you use IE’s unmodified attachEvent() listener. though any sensible cross-browser event handler should solve that IE-issue.