jfox jfox - 9 days ago 6
Javascript Question

How does this href javascript logic work?

I made a mistake and forgot to use the attribute value in some code I was writing:

link = document.getElementsByClassName("summary-title-link")[0];
ele.href = link;



"http://somesite.org/test-link/1"


and I was surprised to see that it still worked regardless.

In extension with this example below, I find it odd that I don't need to target the href attribute before using pathname?

link = document.getElementsByClassName("summary-title-link")[0].pathname;



"/test-link/1"

Answer

When you convert an anchor element to a string, you actually get the href value, or more precisely "the whole URL", and not the outerHTML as you would with most other elements, that's why it works

var href = document.getElementsByClassName("test")[0]; // DOM element

console.log(href.toString()); // gives you "http://google.com"
<a class="test" href="http://google.com">link</a>

This special behaviour for anchors is specified in the specification

HTMLHyperlinkElementUtils.toString()

Returns a USVString containing the whole URL.
It is a synonym for URLUtils.href, though it can't be used to modify the value.