Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting relative paths to absolute with JavaScript

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.

like image 927
James Avatar asked Mar 06 '11 14:03

James


2 Answers

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
});
like image 112
user113716 Avatar answered Sep 20 '22 21:09

user113716


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

like image 31
William Denniss Avatar answered Sep 20 '22 21:09

William Denniss