Check if links are external with jQuery/javascript.

To check if a link is external or not with jQuery/JavaScript, you can use the following code:

<script type="text/javascript">
var comp = new RegExp(location.hostname);

jQuery('a').each(function(){
 //location.hostname === this.hostname || !this.hostname.length 
   if(comp.test(jQuery(this).attr('href'))){
       // a link that contains the current host           
       jQuery(this).addClass('local');
   }
   else{
       // a link that does not contain the current host
       jQuery(this).attr('rel','nofollow');
   }
});
</script>

This code uses the jQuery “each” method to loop through all the links on the page, and then checks each link’s “href” attribute to see if it matches the current site’s domain. If the link’s domain is different from the current site’s domain, it adds the “target=’_blank’” attribute to open the link in a new tab.

Alternatively, you can use pure JavaScript with the following code:

var links = document.querySelectorAll('a');
for (var i = 0; i < links.length; i++) {
  if (links[i].hostname !== window.location.hostname) {
    links[i].setAttribute('target', '_blank');
  }
}

This code selects all the links on the page using querySelectorAll, and then loops through each link to check if its hostname matches the current site’s hostname. If the link’s hostname is different, it adds the “target=’_blank’” attribute to open the link in a new tab.

By checking if links are external or not with jQuery/JavaScript, you can ensure that external links are opened in a new tab and provide a better user experience for your visitors.

Leave a Reply

Your email address will not be published. Required fields are marked *