views:

25

answers:

1

window.event reports the lowest element in the tree when a click happens. e.g.

<a href="http://server.com/page.aspx" id="anchor">
<span id="span" class="Someclass">
    <strong id="strong">Submit</strong> 
</span> </a>

When you click on the above link and if you have onclick listner at BODY level, the window.event will report that "strong" element got clicked. In the same event, how do I know that the parent is actually an "anchor" tag which has href pointing somewhere? i.e. I am looking for an automatic way for me to know the main element is "anchor" and not "strong" element. I clearly can't do window.event.target.parentNode.parentNode as this will be manual checking. May be somewhere I can follow the "bubbling" of the click event.

Anyone any clue?

+2  A: 

You can check the ancestors automatically.

var element = foo;
while (foo !== document.body) {
    if (foo === someCondition) {
      return foo;
    }
    foo = foo.parentNode;
}
return false;

Most libraries have a method to do this built in. e.g. YUI 3 has Node.ancestor, and jQuery has closest.

David Dorward
Hmmm...thanks..I can't use YUI/jQuery as my script is standalone and want to keep very small so. I'll take a look.
Rac123