htmlhref

How to embed path to the current path at anchor href?


For example, right now I'm at http://example.com/practice

If I have a link within the generated page: <a href="5">Click here</a>, I'm directed to http://example.com/5.

Now I know that this is the usual method of relative path. But what I actually need here is so that the link will take me to http://example.com/practice/5 without I need to specify practice or example.com on that page. Preferred if not using any Javascript if possible, but if it is not possible, then I guess I'll have to use Javascript then.

I've already tried <a href="./5">Click here</a> and <a href="./5/">Click here</a> and they still work exactly like "5".

Please help. Thanks.


Solution

  • You can do something in your javascript where you grab the current location with window.location.href (there may be a better way depending if you're using any js frameworks). For example for this page, window.location.href returns https://stackoverflow.com/questions/38284340/how-to-embed-path-to-the-current-path-at-anchor-href

    You could then do something like this

    var baseUrl = window.location.href;
    var aTag = document.querySelector(<selector for your anchor tag>);
    aTag.setAttribute("href", baseUrl + "/" + <url we want to go to>);
    

    So essentially we grab our current location, change the href of the tag we want to navigate to, then add whatever subroute we want to go to at the end. Kind of a weird way to do it, but like I said earlier, there may be an easier way if you're using react or angular or some other framework or library.