Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the full URI from the href property of a link

I would like to have a confirmation on some point.

My goal is to always get the same string (which is the URI in my case) while reading the href property from a link. Example:

<a href="test.htm" /> with base_url = http://domain.name/

<a href="../test.htm" /> with base_url = http://domain.name/domain/

<a href="http://domain.name/test.htm" /> with base_url = any folder from http://domain.name/

I need to get http://domain.name/test.htm from the 3 situations above (or any other identical string).

After some tests, it appears that my_a_dom_node.href always return the full-qualified URI, including the http://domaine.name, which should be okay for what I want.

jQuery has a different behaviour and $(my_a_dom_node).attr('href') returns the content (text) that appears inside the HTML. So my trick is to use $(my_a_dom_node).get(0).href to get the full URI.

The question is: can I rely on this?

like image 460
Savageman Avatar asked Apr 14 '10 16:04

Savageman


2 Answers

YES, you can rely!

Once when people was using simple javascript (no jQuery) many asked the opposite of what you are asking, they wanted to get the real url as written in the href attribute and not the full one, in such case they used to simply do:

my_a_dom_node.getAttribute('href', 2); //works both IE/FF

Then it came jQuery that helped people not to waste their time in finding out they would need such code and jQuery always returns the real url as written in the href attribute.

It's funny that now someone is asking how to get the full url because jQuery returns the one written in the href attribute.

like image 85
Marco Demaio Avatar answered Nov 12 '22 15:11

Marco Demaio


I know it's an old question, but this being actually the first entry that popped up, I believe it's good to add an extra solution. Ever since jQuery introduced the "prop" function, getting the full URL is as simple as:

$(my_a_dom_node).prop('href');

I hope that still helps somebody.

like image 42
arakell Avatar answered Nov 12 '22 14:11

arakell