Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the a.href property always returned as absolute?

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.

like image 351
Flash Avatar asked Apr 29 '11 00:04

Flash


People also ask

How do you make an href absolute?

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 ).

How do you know if a URL is relative or absolute?

URL contains "://" anywhere after the first character, or. URL starts with "//" (protocol relative)

What is the property value of href?

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.

Is href a property?

href property is a stringifier that returns a string containing the whole URL, and allows the href to be updated.


1 Answers

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/

like image 156
Šime Vidas Avatar answered Nov 15 '22 19:11

Šime Vidas