Having such an html:
<a class="someclass" href="some/url/absolute/or/relative">Blah</a>
… along with such javascript:
$("a.someclass").onclick(function() {
var link = $(this).attr("href");
if (link == window.location) // <<<<<<<<<<<<
doSomethingSpecial();
else
doOtherThing();
return false;
});
this code obviously doesn’t work.
How to reliably detect that some anchor is leading to the current browser location?
Here are some notes:
- Anchor’s
hrefcould be either absolute or relative. - the fragments of the URLs should be ignored.
The problem is that
$('a').attr('href')always returns the relative path. You need to use the nativeobj.hrefattribute to get the absolute path, strip hashes and then compare:EDIT:
If you want to compare pathnames, you can grab it directly from the anchor element: