JSFiddle - React, Tailwind, and code Playground

by userdude

HTML

<ol>
    <li>
        <a href="#link1" target="open">Link 1</a> - 
        No enhance class, should be subject to <strong>BASE HREF</strong>: 
        <strong class="p">&raquo; http://example.com#link1</strong>
    </li>
    <li>
        <a href="#link2" class="enhance" target="open">Link 2</a> - 
        Has enhance class, should be:
        <strong class="p">&raquo; http://fiddle.jshell.net/_display/#link2</strong>
    </li>
    <li>
        <a href="#link3" class="enhance" target="open">Link 3</a> - 
        Has enhance class, should be:
        <strong class="p">&raquo; http://fiddle.jshell.net/_display/#link3</strong>
    </li>
    <li>
        <a href="#link3" class="enhance" target="open">Link 4</a> - 
        Has enhance class, should be:
        <strong class="p">&raquo; http://fiddle.jshell.net/_display/#link4</strong>
    </li>
</ol>

CSS

/* This is a fiddle hack so I can set the `base` element, ignore. */
</style>
<base href="https://example.com"/>
<style>
body {
    font-size: 14px;
    font-family: monospace;
}
strong.p {
    padding-left: 57px;
    display: block;
}

JavaScript

//--
// window.onload is not preferred, window.addEventListener
// should be used. Except that only IE9 supports it, and
// IE8 and lower do not support it, and uses window.attachEvent
// instead, which you can test for. 
// I'm using window.onload here simply as a shortcut method and
// for clarity. This can also go in a script tag at the bottom
// of the body tag, in which case you can remove window.onload
// and use a self-calling anonymous function like:
//
//     (function updateLinks(){... all the same as below ...})();
//
// This will ensure you are out of the global variable scope.
//--
window.onload = function updateLinks() {
    //--
    // Modern browsers can use document.getElementsByClassName
    // or you can use a shiv script to add it to browsers that 
    // don't. I'll do it the "manual" way here, and this works
    // cross-browser. The downside is that it will interate 
    // through every A tag on the page, looking for the "small"
    // few that have the el.className we're looking for here.
    //--
    var els = document.getElementsByTagName("a"),
        l = els.length,
        trueURL = '//' + location.host + location.pathname,
        i, el, hash;
    
    for (i = 0; i < l; i++) {
        el = els[i];
        
        if (el.className.indexOf("enhance") != -1) {
            hash = el.href.split('#');
            console.log(hash);
            el.href = trueURL + "#" + hash[1];
        }
    }
};