Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  122] [ 3]  / answers: 1 / hits: 16891  / 14 Years ago, sun, march 6, 2011, 12:00:00

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.


More From » jquery

 Answers
42

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
});

[#93410] Friday, March 4, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleedayanarar

Total Points: 303
Total Questions: 90
Total Answers: 102

Location: Virgin Islands (U.S.)
Member since Tue, Jul 7, 2020
4 Years ago
;