Skip to content
JAVASCRIPT JQUERY

Check if links are external with jQuery/javascript.

A
Author
Aug 30, 2021 · 3 min read
Check if links are external with jQuery/javascript.

TWhen building a website, it’s often useful to determine whether a link is external or internal. External links direct users to a different domain, whereas internal links keep them within the same site. To enhance user experience and SEO, many developers prefer opening external links in a new tab while keeping internal links unchanged.

In this article, we will explore how to check if a link is external using both jQuery and pure JavaScript. We will also discuss different approaches to handling external links for better usability.

Why Identify External Links?

Before diving into the code, let’s explore why identifying external links is important:

  1. Better User Experience – Keeping users on the same tab for internal links while opening external links in a new tab prevents them from losing track of your website.
  2. SEO Considerations – Adding rel="nofollow" to external links prevents search engines from following them, reducing the risk of passing link equity to unknown sites.
  3. Security – External links can be potential security risks. Identifying them allows developers to add security attributes like rel="noopener noreferrer".

Checking If a Link is External Using jQuery

jQuery provides a simple way to loop through all <a> tags and check their hostname. Here’s a script that does this:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function () {
    var currentDomain = new RegExp(location.hostname);

    $('a').each(function () {
      var link = $(this).attr('href');

      if (link && !currentDomain.test(link)) {
        $(this).attr('target', '_blank').attr('rel', 'noopener noreferrer');
      }
    });
  });
</script>

Explanation of the Code:

  • We create a RegExp object using the current domain (location.hostname).
  • We loop through all <a> elements using each().
  • If a link does not contain the current domain, it is considered external.
  • We add the target="_blank" attribute to open it in a new tab and rel="noopener noreferrer" for security.

Checking If a Link is External Using Pure JavaScript

If you prefer not to use jQuery, you can achieve the same functionality using vanilla JavaScript:

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

    links.forEach(function (link) {
      if (link.hostname && link.hostname !== window.location.hostname) {
        link.setAttribute('target', '_blank');
        link.setAttribute('rel', 'noopener noreferrer');
      }
    });
  });
</script>

How This Works:

  • We wait for the DOMContentLoaded event to ensure the script runs after the page loads.
  • querySelectorAll('a') selects all anchor tags.
  • We use forEach() to loop through each link.
  • If link.hostname is different from window.location.hostname, it is external.
  • We then add the necessary attributes (target="_blank" and rel="noopener noreferrer").

Enhancing External Link Security

Apart from opening external links in a new tab, it’s important to consider security. Here are two key security attributes:

  1. rel="noopener noreferrer"
    • Prevents the new tab from accessing window.opener, which can be exploited in phishing attacks.
    • noopener prevents the new tab from controlling the original page.
    • noreferrer prevents referrer information from being sent.
  2. rel="nofollow"
    • Tells search engines not to pass link equity to external sites, which is useful when linking to untrusted sources.

How to Add These Attributes Using JavaScript:

document.querySelectorAll('a').forEach(link => {
  if (link.hostname !== window.location.hostname) {
    link.setAttribute('rel', 'nofollow noopener noreferrer');
  }
});

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');
  }
}

Final Thoughts

Checking if a link is external or internal is a simple but effective way to improve user experience, SEO, and security.

Key Takeaways:

  • Use JavaScript or jQuery to check if a link is external.
  • Open external links in a new tab (target="_blank") for better user experience.
  • Add rel="noopener noreferrer" for security and rel="nofollow" for SEO.
  • Use CSS to visually highlight external links.
A
Author

Author at The Creative Coders.

The monthly build log

One email a month. New posts, lessons, and the occasional strong opinion. No spam.