skip to Main Content

I am trying to modify a site to make it open external links in a new tab.

Currently I have a loop which works fine except that it opens ALL links in a new tab which is not desired:
I have tried using filters but can’t seem to get it to work properly.

<script>
document.addEventListener('DOMContentLoaded', function(){
let links = document.getElementsByTagName('a');

for(var i=0;i<links.length;i++){
  links[i].setAttribute('target','_blank');
}
});
</script>

Maybe checking if the URL contains a Shopify handle or something along the line?

Thank you in advance!

3

Answers


  1. You can check if the href attributes begins with http://, https:// or www. since those are the most common external links, all internal usually starts with /. (you can add an additional check if the href contains the domain name as well since it possible to have internal URL with the full URL)

    So the code will become something like so:

    document.addEventListener('DOMContentLoaded', function(){
      const links = document.getElementsByTagName('a');
    
      for(var i=0;i<links.length;i++){
        const link = links[i];
        const href = link.getAttribute('href');
        if(href.match(/^((https?://)|(www.))/) {
          link.setAttribute('target','_blank');
        }
      }
    });
    
    Login or Signup to reply.
  2. Maybe something like this?

    const links = document.querySelectorAll("a"); //get all <a> elements
    
    links.forEach(el => { //loop trought all <a> elements
      if(!el.href.includes(window.location.hostname)){ //if not this domain
       el.setAttribute("target", "_blank");
      }
    })
    /*just to show elements with target=_blank*/
    [target="_blank"]{
    color: green
    }
    <a href="//google.com">other domain</a>
    <a href="//stacksnippets.net">this domain</a>

    Note: you don’t need that document.addEventListener('DOMContentLoaded'... just put defer attribute on your <script> tag

    Login or Signup to reply.
  3. To get only External links Open in new Tabs, you must use anchor’s property hostname, when its value not matching your “localhostname” string then overwriting anchor’s property target default value "_self"(current browser content) to "_blank"(new tab) value, your script code will be:

    <script> 
    document.addEventListener('DOMContentLoaded', function(){
     let links = document.getElementsByTagName('a'); 
    for(var i=0;i<links.length;i++){
     if (links[i].hostname!="localhostname"){ 
        links[i].setAttribute('target','_blank');
       } 
      }
     }); 
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search