0

When we click one <a> tag the browser gets redirected to the corresponding page, but there are some details. Consider the following examples:

<a href="../onepage.html">One Page</a>
<a href="http://example.com/onepage.html">One Page</a>
<a href="onepage">One Page</a>
<a href="onepage.html">One Page</a>

When we visit such page with a browser it will in some sense translate those. If the address of the page on which this is located is http://www.example.com/pages/somepage.html the first will be translated to a redirect to http://www.example.com/onepage.html, the second will stay as it is, the third will be translated to a redirect into http://www.example.com/onepage and the last one will also be like the third.

My question is: how can, using jQuery, we get those "translated versions" of the URLs? This is not the href since this will give the information "as is".

How can we get with jQuery the URL a browser will actually follow if one clicks the link?

user1620696
  • 10,825
  • 13
  • 60
  • 81

2 Answers2

0

What you are looking for is how to convert relative links to absolute ones. I think this question has been answered in multiple forms in this answer

Rather than having urls as input, you can use a jquery selector to get say the first <a> tag using $('a')[0] (or use your favorite jquery method) and use that as the link variable used in the linked solution.

Community
  • 1
  • 1
Dennis Shtatnov
  • 1,333
  • 11
  • 17
0

You can do this in jQuery with .prop('href'). This is one of the cases where there's a difference between .prop() and .attr(). .attr() returns the raw attribute from the DOM element, but .prop returns the href property that results from parsing the URL.

In plain Javascript these would be element.href and element.getAttribute('href').

$("a").each(function() {
  console.log('.attr: ' + $(this).attr('href') + ' .prop: ' + $(this).prop('href'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="../onepage.html">One Page</a>
<a href="http://example.com/onepage.html">One Page</a>
<a href="onepage">One Page</a>
<a href="onepage.html">One Page</a>
Barmar
  • 741,623
  • 53
  • 500
  • 612