Get The Full Uri From The Href Property Of A Link
Solution 1:
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.
Solution 2:
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.
Solution 3:
Yes, you can rely on this.
Looking through the jQuery (1.4.2) source code, I see the jQuery.attr()
function being used (condensed to the relevant parts):
jQuery.extend({
// ...attr: function( elem, name, value, pass ) {
// ...var attr = !jQuery.support.hrefNormalized && notxml && special ?
// Some attributes require a special call on IE
elem.getAttribute( name, 2 ) :
elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefinedreturn attr === null ? undefined : attr;
}
});
So it´effectively calls elem.getAttribute('href')
which returns the actual attribute value, while the href
property by design returns the canonical URL.
However, there is a reference to jQuery.support.hrefNormalized
, of which the jQuery support site has to say:
hrefNormalized
: Is equal to true if the.getAttribute()
method retrieves thehref
attribute of elements unchanged, rather than normalizing it to a fully-qualified URL. (It is currently false in IE, the URLs are normalized). DOM l3 spec
This basically means that jQuery finds out browser behavior on its own and adapts accordingly to provide a consistent result.
Solution 4:
You could recompose the full url using a bit of javascript :
function parseLink(link) {
var baseUrl = location.href.substring(0,location.href.lastIndexOf('/'));
if (link.indexOf('/') != -1) {
link = link.substring(link.lastIndexOf('/'));
} else {
link = "/"+ link;
}
var fullUrl = baseUrl + link;
return fullUrl
}
Post a Comment for "Get The Full Uri From The Href Property Of A Link"