I am trying to do something in JavaScript before following the link in the href part of a link:
<a href="open.this.page" onclick="doStuff(this);return false; title="follow me">
Question is what does this in doSuff(this) refer to? I was expecting to have to get the href part of the anchor out of it, but when examining it looks like it IS the href and nothing else.
function doSutff(my_arg) {
alert (my_arg);
// do stuff
// follow the href in the link
}
In the above alert I get exactly the href as "http://my.domain/open.this.page".
Is this expected or am I getting it in one browser, but probably not in another?
If that is the normal behavior then how would one get, for example, the rel or title part of an anchor? DOM only?
This is expected. The reason you get
"http://my.domain/open.this.page"in the alert is that that is what the default.toString()value is of an<a>element.It’s an unusual case. Other elements don’t show an attribute as the
.toString()representation.If you want to actually do work with the
href, you’d need to dothis.toString(), or see below…To get other attributes or properties, you’d just do it the usual ways.
To get the attribute, you can do:
Most of the standard attributes map directly to a property on the node, so you could also do this:
Or since you’re in an inline handler, you can actually do this:
The reason that last one works is that handlers assigned from an attribute have a unique scope chain that includes the element itself. This means that properties on the element actually show up as variables.
Note that this doesn’t work for any other kind of event handler.
With regard to
this, it refers to the element to which the handler is bound.What happens to the attribute is that it basically becomes the body of a function assigned to the
onclickproperty.So you end up with something like this:
So you can see that
thisis actually just the normal value found in an event handler assigned to a property.Notice also that there’s an
eventparameter defined. This means that you could change your attribute like this:…and it will pass on that parameter, because now your function looks like this:
So you can see that your string is actually referencing the normal
eventparameter of the function.This also works in older IE. In IE, the
eventparameter won’t be defined, so it’ll pick up the globaleventobject.