HTML:
<a href="/">1</a> // link to http://site.com
<a href="/section/page/">2/a> // link to http://site.com/section/page/
<a href="http://site.com/">3</a>
<a href="../gallery/1/">4</a> // link to http://site.com/gallery/1/
JS:
$("a").live('click', function(){
var url = $(this).attr("href");
//do something
});
How to convert relative path (var url
) to absolute by jQuery?
Script should do nothing, if it is already an absolute path.
Thanks.
I'm pretty sure that if you use the href
property instead of getting the attribute, you'll have a full url with domain:
$("a").live('click', function(){
var url = this.href; // use the property instead of attribute
//do something
});
As noted in the question linked by @Phrogz, it sounds as though there are issues with IE6.
If you need to support it, you may need to build the href
from the different parts like this.host
and this.pathname
. Those properties are supported by IE6. There are others you could use too, but you'd need to verify support.
jquery live() function deprecated in version 1.7 and removed from 1.9 so use alternate on():
$("a").on('click', function(){
var url = this.href; // use the property instead of attribute
//do something
});
Not what the OP asked, but if anyone is trying to do this for <img>
tags (as I was when I found this Question), the secret it not to use jQuery's attr method.
This gives you straight contents of the src attribute (which if it's relative, will be relative):
$('#your_img').attr('src')
Whereas calling .src on the DOM object itself always gives you the absolute path (what I needed):
$('#your_img').get(0).src
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