jfox jfox - 1 year ago 67
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;


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;


Answer Source

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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download