Search code examples
javascriptanchor

Excluding a Site Anchor Link JavaScript


I do have this code:

<script>
    var link = document.getElementsByTagName("a:not(#)");
    
    for (var i = 0; i < link.length; i++) {
        link[i].href = link[i].href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
    }
    </script>

The code should lookup for all a tags on the Site and replace all UTMs. Works so far. But there are Anchor Tags on the site which are now broken.

In the code of the site the Link looks like:

<a href="#newspaper" class="someclass">Newspaper</a>

When I hover over the Link it shows me:

https://www.mysite.or/#newspaper

How do I exclude those Anchor Tags?


Solution

  • This code return all links exclude anchors

    document.querySelectorAll('a:not([href*="#"])');