When I use the html tag to define a base URL for all relative links on a page, anchor links also refer directly to the base URL. Is there a way to
My approach is to search for all links to an anchor, and prefix them with the document URL.
This only requires javascript on the initial page load and preserves browser features like opening links in a new tab. It also and doesn't depend on jQuery/etc.
document.addEventListener('DOMContentLoaded', function() {
// get the current URL, removing any fragment
var documentUrl = document.location.href.replace(/#.*$/, '')
// iterate through all links
var linkEls = document.getElementsByTagName('A')
for (var linkIndex = 0; linkIndex < linkEls.length; linkIndex++) {
var linkEl = linkEls[linkIndex]
// ignore links that don't begin with #
if (!linkEl.getAttribute('href').match(/^#/)) {
continue;
}
// convert to an absolute url
linkEl.setAttribute('href', documentUrl + linkEl.getAttribute('href'))
}
})