I have a link with this href:
href="javascript:foo(this);"
when I call it "this" points to the window object, not the link. How do I pass a reference to the link?
/
Edit note: The question is how to pass with href, not generally - I know about onclick!
And not copying id and make getElementById, that's not "this", it's DOM search for certain element, no need to make it inline in HTML.
The anwer is: not possible.
I have a link with this href:
href="javascript:foo(this);"
when I call it "this" points to the window object, not the link. How do I pass a reference to the link?
http://jsfiddle.net/xMGKz/
Edit note: The question is how to pass with href, not generally - I know about onclick!
And not copying id and make getElementById, that's not "this", it's DOM search for certain element, no need to make it inline in HTML.
The anwer is: not possible.
Share Improve this question edited Mar 14, 2012 at 12:43 ixx asked Mar 14, 2012 at 12:32 ixxixx 32.3k41 gold badges137 silver badges237 bronze badges4 Answers
Reset to default 24When you use "javascript: .... " in an href, you are calling this function globaly. Not in the context of the link. You can try with:
<a href="#" onclick="foo(this); return false;">MyLink</a>
http://jsfiddle.net/xMGKz/1/
subjectively you would be better suited with something like:
<a href="javascript:void(0)" id="myAnchor">My Link</a>
and then to code:
document.getElementById('myAnchor').onclick = function() {
// this is the <a> in here
return false; // optional, prevents href from executing at all
};
this way everything is a little more clear. hope this helps -ck
Better to;
<a href="javascript:void(0)" onclick="alert(this.href);">Link</a>
First, add an ID field to your anchor.
Then...
Using standard Javascript:
<a id="someLink" href="javascript:foo(document.getElementById('someLink'));">
Using jQuery:
<a id="someLink" href="javascript:foo($('#someLink'));">