In the following HTML:
<a id="link" href="page.htm">Page</a>
I'm finding that document.getElementById("link").href
always returns the absolute path to page.htm
rather than the relative path as I have typed it. See http://jsfiddle.net/4HgAW/.
Can I guarantee that javascript will always return the absolute path, in every browser?
The reason I'm asking is that I'm grabbing the http://www....
part to check which domain the link points to, and I need it to work for internal links as well.
If you prefix the URL with // it will be treated as an absolute one. For example: <a href="//google.com">Google</a> . Keep in mind this will use the same protocol the page is being served with (e.g. if your page's URL is https://path/to/page the resulting URL will be https://google.com ).
URL contains "://" anywhere after the first character, or. URL starts with "//" (protocol relative)
Property ValuesSpecifies the URL of the link. Possible values: An absolute URL - points to another web site (like href="http://www.example.com/default.htm") A relative URL - points to a file within a web site (like href="default.
href property is a stringifier that returns a string containing the whole URL, and allows the href to be updated.
Yes, all relevant browsers return the fully qualified URL.
If you want to retrieve the original value of the href
attribute ('page.html' in this case), you can do this:
anchor.getAttribute('href')
However, that doesn't seem to work in older versions of IE (8 and below).
Live demo: http://jsfiddle.net/simevidas/4HgAW/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With