1

I am using some JS code to find all internal links on a page and add a subfolder to them. This code is used on translated pages so internal links to other translated pages are correct.

I want to have this code update all internal links, unless they have a class attribute.

If the class attribute exists, I want the link to be ignored by the JavaScript function.

<a class="noTranslateLink" href="domain.com"

<script>
    function replace_url(elem, attr) {
        var elems = document.getElementsByTagName(elem);
        for (var i = 0; i < elems.length; i++)
            elems[i][attr] = elems[i][attr].replace('<?php echo $_SERVER['HTTP_HOST'] ?>', '<?php echo $_SERVER['HTTP_HOST'] ?>/ru');
    }
    window.onload = function() {
        replace_url('a', 'href');
    }
</script>

2 Answers 2

1

I have not tested, But this must work:

function replace_url(elem, attr) {
  var elems = document.getElementsByTagName(elem);
  for (var i = 0; i < elems.length; i++) {
    if (elems[i].getAttribute('class') != "noTranslateLink")
      elems[i].setAttribute(attr,elems[i].setAttribute(attr).replace('',''));

  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, nice and simple. swap == for != to reverse condition. Great, thanks!
Oh Yes, that was a tyop. Let me edit this in the answer :) Thanks!
1

To select all anchor elements with no class attribute:

var elems = document.querySelectorAll(elem + ':not([class])');

The opposite is:

var elems = document.querySelectorAll(elem + '[class]');

1 Comment

Thanks, hover it seems to work the same as my code. <script> function replace_url(elem, attr) { var elems = document.querySelectorAll(elem + ':not([noTranslate])'); for (var i = 0; i < elems.length; i++) elems[i][attr] = elems[i][attr].replace('<?php echo $_SERVER['HTTP_HOST'] ?>', '<?php echo $_SERVER['HTTP_HOST'] ?>/ru'); } window.onload = function() { replace_url('a', 'href'); } </script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.