Getting source element of onclick event

I’m trying to add an onclick of a link and, in the handler function, get a reference to the clicked element.
I thought this code should work, and work across browsers:

<script>
function getit(e)
{
	if (!e) var e = window.event;
	alert(e);
}
</script>
<a href='#' onclick="getit(); return false;">click</a>

Works fine in IE However in firefox e is undefined. What am i doing wrong?

I know it’s possible, so I wanted to figure it out rather than resort to passing ‘this’ along with every function call.


function getit(el)
{
    alert(el);
}
<a href='#' onclick="getit(this); return false;">click</a>

Much neater, though, would be to “get it” via its ID (or via other DOM methods):

var el = document.getElementById('alink');
el.onclick = doStuff;
function doStuff() {
  this.firstChild.nodeValue = 'I\\'ve been clicked!';
}
<a href="#" id="alink">click</a>

I’d recommend giving this a read.

http://www.quirksmode.org/js/introevents.html#link11

Yes, I could use ‘this’, and I might have to in the end, but why doesn’t the method work as it is?

if (!e) var e = window.event;

According to everything I’ve read, this should give a reference to the event.

And there are a lot of links, all with different arguments to pass to the function, so I was trying to avoid adding the onclick via script, though I agree it is usually neater.

Just for my own learning, rather than solving the problem with a different approach (using ‘this’), I’d like to figure out detecting the source element of the click.

Any ideas?

See this: http://www.quirksmode.org/js/events_access.html#link6

I think I get it now. Assigning the onclick handler inline, you have to pass the event to the function, but you don’t have to do this when assigning the onclick via script, hence my getting a little confused.
Ta for the help.