Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get full URL from a hyperlink using jQuery / JavaScript

How can I retrieve the full URL to which an anchor links using jQuery / JavaScript consistently across all browsers? For example, I want to return http://www.mysite.com/mypage.aspx from <a href="../mypage.aspx"></a>.

I have tried the following:

  1. $(this).attr('href'): The problem is that jQuery returns the exact value of the href (i.e., ../mypage.aspx).

  2. this.getAttribute('href'): This works in Internet Explorer, but in FireFox it behaves the same as above.

What is the alternative? I cannot simply append the current site's path to the href value because that would not work in the above case in which the value of the href escapes the current directory.

like image 518
Devin Burke Avatar asked Nov 28 '11 04:11

Devin Burke


People also ask

How can I get full URL of href?

Answer: Use the window. location. href Property location. href property to get the entire URL of the current page which includes host name, query string, fragment identifier, etc. The following example will display the current url of the page on click of the button.

How can I get URL in jQuery?

Answer: Use the syntax $(location). attr("href"); You can use the Location object and jQuery attr() method to get the URL of the current page.

How can get current URL with parameters in jQuery?

In JavaScript, just use window. location. href, and in JQuery use code $(location). attr('href'), both will return the current URL.

Which method return the URL of the current page?

The window.location.href property returns the URL of the current page.


1 Answers

You can create an img element and then set the src attribute to the retrieved href value. Then when you retrieve the src attribute it will be fully qualified. Here is an example function that I have used from http://james.padolsey.com/javascript/getting-a-fully-qualified-url/:

function qualifyURL(url){
    var img = document.createElement('img');
    img.src = url; // set string url
    url = img.src; // get qualified url
    img.src = null; // no server request
    return url;
}
like image 68
Brian Fisher Avatar answered Nov 01 '22 22:11

Brian Fisher