PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » jQuery » Target Only External Links

Target Only External Links

Technique #1

$('a').filter(function() {
   return this.hostname && this.hostname !== location.hostname;
}).addClass("external");

Technique #2

$.expr[':'].external = function(obj) {
    return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname);
};
$('a:external').addClass('external');

Technique #3

$('a:not([href^="http://your-website.com"]):not([href^="#"]):not([href^="/"])').addClass('external');

Technique #4

$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if (!a.test(this.href)) {
       // This is an external link
   }
});

Subscribe to The Thread

  1. Reference URL no longer works.

    • I guess the author took it down… sorry about that. I removed that link and added an additional technique.

  2. Any info on which of these is optimal for performance? (I’m guessing not #4 heheh)

    • I actually have no idea, that would be good to know.

    • Why does #4 create a new regular expression object on every iteration of the loop? That’d be pretty slow, as it’d have to parse the regexp on every iteration. I think it’d be significantly faster to create one RegExp, before the loop starts.

  3. This is great, but I\m new to jquery – so how do you use this code? I assume it goes int he head somewhere, and then have a css style for ‘external’ – but does it need script tags etc?

  4. Do it with CSS:

    a[href^="http://"]{ /*Style an external link here*/ }

    • Nice – but this wouldn’t work if you have a CMS system that uses absolute urls (I think WordPress does this?)

    • Can you use this CSS technique to insert this:
      target=”_blank”
      into the href tag? I want to find all external links on a page and open them in a separate window, not style them.

  5. why not use document.domain rather than manually typing in the domain?

  6. Jon Spencer

    @Rory – You can do it that way :)

    a[target="_blank"] { yourstyle: style !important; }

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~