Skip to content Skip to sidebar Skip to footer

Javascript 'this' Keyword Returning Href Attribute Rather Than Object On Anchor Tag

Requirement: Return the element object. Problem: Using the code below, I expected the links to return [object], but they actually return the string in the href attribute (or in the

Solution 1:

As you said, accessing a property in the second and third link works. That means that this is indeed the A DOM element but when it is converted to a string (which is what happens when you want to alert it) it is converted to the URL.

So you already have your object ;)

Same happens when you do alert(document.location). It is actually an object but when converted to a string, it prints the current location.

Solution 2:

When alert is invoked, the toString method is internally invoked so for the case of the anchors alerting the href, the toString of anchors returns the href instead.

<a id="foo" href="blah">fsdjl</a>

In the JS console, do:

document.getElementById('foo').toString()

This would confirm it.

As for window, this isn't bound to a method owned by the anchor, so this refers to the global context. onclick is bound to the anchor so this, aka current execution context, changes to the anchor.

<ahref="#"onclick="javascript:alert( this.nodeName )">blah</a>

The result is it alerts A which is the nodeName, so the browser does return the href if there is an href set so it's more "readable" and less vague.

Post a Comment for "Javascript 'this' Keyword Returning Href Attribute Rather Than Object On Anchor Tag"