Reputation:
<a onclick ="foo()" href="bar.html" >Link </a>
<script>
...
function foo(){
//I want to know the href property of whoever called me.
//something like this.caller.href ??
}
</script>
I guess I could just assign all element IDs and then pass my own ID to the JS method I'm calling, but I was looking for a better way.
Upvotes: 16
Views: 19825
Reputation: 601
<a onclick="foo(this)" href="bar.html">Link</a>
Then your JavaScript would be:
function foo(ob) {
alert(ob.href); //or whatever you want to happen preferably pass an id
}
Use the "this" selector if you want to pass the object itself to the function.
Upvotes: 11
Reputation: 144162
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.
Upvotes: 19
Reputation: 45731
The convention here is that this refers to the DOM element that the handler is invoked on. So if you want to know the href of the link:
function foo () {
// Inside foo this will refer to the DOM element if called as an event handler
var href = this.href
}
That should do the trick.
EDIT: If foo is called from an onclick-handler explicitly in the DOM, i.e.
<a [...] onclick="foo()">
then the original context of this will be lost inside of foo. To fix this one can bind the function call to the original context:
<a [...] onclick="foo.call(this)">
Upvotes: 2
Reputation: 59648
you don't need to pass in the element as an argument to your function. you can use
var a = event.srcElement;
alert(a.href);
Upvotes: 0
Reputation: 35351
You could pass the value of the href
attribute to the function when it is called:
<a href="http://www.example.com" onclick="foo(this.href)">link</a>
Upvotes: 1