[jQuery] How do I get the actual HREF of a link?
Here's the short version:
I have a link:
<a id="testlink" href="page.html">page.html</a>
But when I do this:
alert($('#testlink')[0].href);
I get this:
http://localhost/page.html
How do I get the *actual* HREF of the link ("page.html"), and not the
mangled version?
Thanks!
----------
The long version:
I have a few links in HTML:
<a href="/page1.html">/page1.html</a>
<a href="http://localhost/page1.html">http://localhost/page1.html</
a>
<a href="http://localhost:80/page1.html">http://localhost:80/
page1.html</a>
<a href="http://localhost/page2.html">http://localhost/page2.html</
a>
<a href="http://www.google.com/page1.html">http://www.google.com/
page1.html</a>
When I do this:
$("[href]").each(function() {
var matches = $("[href='" + this.href + "']");
console.log("Searching for HREF \"" + this.href + "\", text
\"" + $(this).html() + "\"" );
matches.each(function() {
console.log("Found: HREF \"" + this.href + "\", text \"" +
$(this).html() + "\"" );
});
});
I get this:
Searching for HREF "http://localhost/page1.html", text "/
page1.html"
Found: HREF "http://localhost/page1.html", text "http://localhost/
page1.html"
Searching for HREF "http://localhost/page1.html", text "http://
localhost/page1.html"
Found: HREF "http://localhost/page1.html", text "http://localhost/
page1.html"
Searching for HREF "http://localhost/page1.html", text "http://
localhost:80/page1.html"
Found: HREF "http://localhost/page1.html", text "http://localhost/
page1.html"
Searching for HREF "http://localhost/page2.html", text "http://
localhost/page2.html"
Found: HREF "http://localhost/page2.html", text "http://localhost/
page2.html"
Searching for HREF "http://www.google.com/page1.html", text
"http://www.google.com/page1.html"
Found: HREF "http://www.google.com/page1.html", text "http://
www.google.com/page1.html"
The problem is that elem.href is returning a mangled version of the
HREF, but the [href='...'] selector requires the URL exactly as it is
written in the HTML. So when an element has "/page.html" as it's
HREF, doing elem.href returns "http://localhost/page.html" instead.
So to search for the "/page.html" HREF, I have to search for:
[href='page.html']
[href='/page.html']
[href='http://localhost/page.html']
[href='http://localhost:80/page.html']
[href='https://localhost/page.html']
[href='https://localhost:443/page.html']
Where "localhost" and "80" must be determined by javascript at runtime
to reflect the current server and port. Also, the "/page.html" and
"page.html" are not comprehensive. The javascript would also have to
check for all permutations of "../page.html", "folder/../page.html",
etc. The root of the problem here is this: how can I get the
*actual* HREF of a link via javascript, and not the mangled version?