0

In my html <head>, I have defined the following <base>:

<base href="/" target="_blank">

Now I cannot link to tags with IDs on the same page, such as:

<sup id="ref1" name="ref1"><a href="#fn1" target="_top">1</a></sup>

<p class="footnote" id="fn1" name="fn1">
    <a href="#ref1" title="back" target="_top">&#8617;</a>
</p>

The links to the IDs takes me back to the root directory instead of the ID specified. Can I somehow force the <a> elements to look for the ID in the current document without having to remove the href="/" in <base>?

  • Possible duplicate of [Make anchor links refer to the current page when using ](http://stackoverflow.com/questions/8108836/make-anchor-links-refer-to-the-current-page-when-using-base) – arcyqwerty Feb 20 '16 at 00:13

1 Answers1

0

Try:

$(document).ready(function() {
    var pathname = window.location.href.split('#')[0];
    $('a[href^="#"]').each(function() {
        var $this = $(this),
            link = $this.attr('href');
        $this.attr('href', pathname + link);
    });
});

which will fix all links or (without jQuery) on individual links:

<a href="javascript:;" onclick="document.location.hash='anchor';">Anchor</a>

Source: Make anchor links refer to the current page when using <base>

Community
  • 1
  • 1
arcyqwerty
  • 8,893
  • 2
  • 40
  • 77
  • Thanks, this works. I also found a solution where the following works: `` – Matthias Müller Feb 23 '16 at 14:51
  • Yes, that works too, assuming you're on `path/filename.html`. The provided answer is more general in that it allows you to use relative anchors that don't depend on the page name. For example, if you renamed `filename.html` -> `foo.html`, you would have to change all the links. This also works across different pages (same code for every page). Your solution doesn't use JS though, so that can be desirable as well. – arcyqwerty Feb 23 '16 at 14:55