Search code examples
htmlhrefrootradix

base href to / - now href to IDs not working


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>?


Solution

  • 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>