Tygo
Tygo

Reputation: 192

html base element on 'a' element only

I want to use the HTML 'base' element to change my base directory. But I only want the base directory to be changed for my 'a' elements and not for my script and style includes.

So I found out that I can use base element but I think I cannot really change anything further than this.

<base href="https://example.com/">

//Don't change root for this:
<script src="../js/example.js"></script>

//Only change root for this:
<a href="../example">example</a>

Does anyone know how I could make this work? Maybe javascript or something. But I cannot find anything about this.

I got something like this: (doesn't work)

$('a').each(function() {
     var value = $(this).attr('href');
     $(this).attr('href', 'new/root/' + value);
});

Upvotes: 0

Views: 218

Answers (1)

Win
Win

Reputation: 5584

Welcome to StackOverflow. The easiest way to do this is to grab all the anchor tags by using querySelectorAll. Once you've grabbed all the elements, we can use forEach to iterate over each anchor tag with a function.

The function will grab the href attribute using getAttribute. Once we have the href we use replace to run a quick regular expression that finds all dots and slashes and replace them with empty characters. Now that we removed these characters we can reassign the href using setAttribute.

const allAnchorTags = document.querySelectorAll('a');

allAnchorTags.forEach(function(anchorTag) {
  var href = anchorTag.getAttribute('href');
  var splitHref = href.replace(/\.|\//g, '');
  anchorTag.setAttribute('href', '/'+splitHref);
});

For a list of methods used in the example, see below:

Query Selector All: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Get Attribute: https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

Set Attribute: https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute

Replace: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Upvotes: 4

Related Questions