When the browser calls a function as the result of a DOM event, JavaScript passes an object to that function which contains information about the event. But it works a little differently in IE than others. To work in all browsers, foo()
should take an argument* (I use e
):
function foo(e) {
var sender = (e && e.target) || (window.event && window.event.srcElement);
//sender is the DOM element which was clicked
alert(sender.href); //assumes the clicked element was an <a>
}
The first line will assign "sender" the value of the element which originated the event in all browsers.
Now, if your <a>
contains child elements (for example, an image) and one of those was the actual element clicked, then that element will become the "sender". If this is a possibility, you need to walk up the DOM from the sender until you find your link:
function foo(e) {
var sender = (e && e.target) || (window.event && window.event.srcElement);
//sender is the DOM element which was clicked
var myEle = sender;
//find the parent node until we hit the <a>
while(myEle.tagName.toUpperCase() != 'A') {
myEle = myEle.parentNode;
}
//myEle is now the <a>. sender is still the originator.
alert(myEle.href);
}
*You can also access any arguments passed to the function, even if they are not declared, by using the arguments[]
array.