Target Only External Links

Technique #1

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

Technique #2

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

Technique #3


Technique #4

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


  1. Chordian
    Permalink to comment#

    Reference URL no longer works.

    • Chris Coyier
      Permalink to comment#

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

  2. Jon Raasch
    Permalink to comment#

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

    • Chris Coyier
      Permalink to comment#

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

    • Daniel15
      Permalink to comment#

      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. Andy
    Permalink to comment#

    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. Jack
    Permalink to comment#

    Do it with CSS:

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

    • Andy
      Permalink to comment#

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

    • Rory
      Permalink to comment#

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

    • Mark Battistella
      Permalink to comment#

      Just in case any one comes across this like I did, and wants a CSS only alternative, this is what I used:

      a[href*="//"]:after {content: ">"}

      It is mainly for relative links only, or else your own links will get the content:">"

    • Rob
      Permalink to comment#

      @Rory, the answer to your question, as of March 2015, is no. It’s not possible to force certain links to open a certain way using only CSS. After thinking about it though, that would make things easy while developing websites.

  5. matt mcinvale
    Permalink to comment#

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

  6. Jon Spencer
    Permalink to comment#

    @Rory – You can do it that way :)

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

    • Rob
      Permalink to comment#

      @Jon, I think @Rory was asking if it’s possible to insert code into HTML from CSS, not how to style it.

  7. tushar lapani
    Permalink to comment#

    Hello frds!!
    I have two question here.
    first one is how i can prevent default selection of radio button.

    second one is that how i can open new window in parent window of the current. I have use code like‘mypage.html’ , ‘_parent’)

    what is prob with this code??????

    Help me plzzzzzzzz

  8. jason kühn
    Permalink to comment#

    With pure CSS you can achieve this by setting all links to have the external treatment and using the cascade w/ attribute selectors to target and unset your exclusions. This technique probably won’t work on all browsers (*ahem* oldIE), but it’s handy when you don’t have complete control over how your markup is created—like in a CMS with inconsistant modules/plugins that write markup—where you have a mix of absolute and relative links and no way to apply an class="external", rel="external", target="_blank", etc. and you don’t want to rely on JavaScript.

    /* target all anchors with an href attribute */
    a[href] { 
    	display: inline-block; 
    /* do something special to indicate an external link */
    a[href]:after { 
    	content: ">";
    /* target what you consider to be "internal" links and undo styles */
    a[href^="javascript:"] {
    	display: inline;
    /* undo */
    a[href^="javascript:"]:after {
    	content: none;
  9. ravi

    I am trying to open rss feed on my website to open in new tab but its not working ,I have trying everything ,please help me.i think this script is preventing that to happen.i m new to this.can u please tell me what I need to change in this to external link to open in new tab.
    $(document).ready(function() {
    function filterPath(string) {
    return string
    var locationPath = filterPath(location.pathname);
    var scrollElem = scrollableElement(‘html’, ‘body’);

    $(‘a[href*=#]’).each(function() {
    var thisPath = filterPath(this.pathname) || locationPath;
    if ( locationPath == thisPath
    && (location.hostname == this.hostname || !this.hostname)
    && this.hash.replace(/#/,”) ) {
    var $target = $(this.hash), target = this.hash;
    if (target) {
    var targetOffset = $target.offset().top;
    $(this).click(function(event) {
    $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
    location.hash = target;

    // use the first element that is “scrollable”
    function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
    var el = arguments[i],
    $scrollElement = $(el);
    if ($scrollElement.scrollTop()> 0) {
    return el;
    } else {
    var isScrollable = $scrollElement.scrollTop()> 0;
    if (isScrollable) {
    return el;
    return [];


  10. site
    Permalink to comment#

    hey there and thank you for your information – I have certainly
    picked up something new from right here. I did however
    expertise several technical issues using this web site, since I experienced to reload the website many times previous to I could get it to load properly.
    I had been wondering if your hosting is OK? Not that I am complaining, but slow loading instances
    times will often affect your placement in google
    and could damage your quality score if ads and marketing with Adwords.
    Anyway I’m adding this RSS to my email and can look out for a lot more of your respective intriguing content.
    Make sure you update this again soon.

  11. Bill Hinderman
    Permalink to comment#

    I’m handling it like this right now:

    a, .link
      &[rel*=" external"],
      &[target*="blank "],
      &.external {
        //external styles

    Put it here, as well.

  12. Vinny

    OK this cool an all but… For a begginer like me where do I put this and how? I need it for a website i’m currently working on. Please if you can cater for beginners I need step by step.

    Thank you.

  13. Andrew
    Permalink to comment#

    BOO YAH – love it!
    Thanks Chris for putting together a external link targeting using either:
    CSS selectors or modular jQuery.

    Time saver!

  14. Mark
    Permalink to comment#

    In case anyone is still considering using this, I made a jsperf performance test:

    In the very limited result set, technique #1 is clearly the fastest. I left out technique #3 (didn’t want to hardcode a URL). Technique #4 is the slowest.

  15. Sohaib
    Permalink to comment#

    What if I want to open external site links (further pages) in same div where the site displays, without moving to next page or without changing URL. Just need to open in same div where external site already show.

  16. Zberno
    Permalink to comment#

    @Mark: Variation of #3

    $('a[href^="http://"]:not([href*="' + location.hostname + '"]), a[href^="https://"]:not([href*="' + location.hostname + '"])').addClass('external');


    $('a[href^="http://"]:not([href*="' + location.hostname + '"]), a[href^="https://"]:not([href*="' + location.hostname + '"])').attr('target','_blank');

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

We have a pretty good* newsletter.