71

Let's say I have the following code:

<div id="link_other">
    <ul>
        <li><a href="http://www.google.com/">google</a></li>
        <li>
            <div class="some_class">
                dsalkfnm sladkfm
                <a href="http://www.yahoo.com/">yahoo</a>
            </div>
        </li>
    </ul>
</div>

In this case, the JavaScript would add target="_blank" to all links within the div link_other.

How can I do that using JavaScript?

1
  • 1
    Why not let the JavaScript detect which links are external?
    – James
    Apr 29, 2009 at 22:45

7 Answers 7

150
/* here are two different ways to do this */
//using jquery:
$(document).ready(function(){
  $('#link_other a').attr('target', '_blank');
});

// not using jquery
window.onload = function(){
  var anchors = document.getElementById('link_other').getElementsByTagName('a');
  for (var i=0; i<anchors.length; i++){
    anchors[i].setAttribute('target', '_blank');
  }
}
// jquery is prettier. :-)

You could also add a title tag to notify the user that you are doing this, to warn them, because as has been pointed out, it's not what users expect:

$('#link_other a').attr('target', '_blank').attr('title','This link will open in a new window.');
4
  • 19
    He asked for javascript, not jQuery.
    – Mark
    Dec 6, 2014 at 20:54
  • 1
    To be more precise, you can use for anchors: let anchors = document.querySelectorAll('#sources + div a'); // Change selector And use ES6 instead of for loop: anchors.forEach((elem) => { elem.setAttribute('target', '_blank') }
    – djibe
    Nov 30, 2020 at 16:51
  • How can we do this in react. Feb 17 at 3:14
  • Hello @AhmedShaikh please do add a new question here on Stack Overflow to ask that!
    – artlung
    Feb 21 at 16:44
60

Non-jquery:

// Very old browsers
// var linkList = document.getElementById('link_other').getElementsByTagName('a');

// New browsers (IE8+)
var linkList = document.querySelectorAll('#link_other a');

for(var i in linkList){
 linkList[i].setAttribute('target', '_blank');
}
3
  • 3
    Instead of getAttributesByTagName, shouldn't it be getElementsByTagName? Apr 29, 2009 at 21:17
  • Or just linkList[i].target = '_blank';
    – James
    Apr 29, 2009 at 22:44
  • This version worked like a charm for me in wordpress when adding: target="_blank" to an RSS feed with elementor Dec 4, 2020 at 17:00
8

Bear in mind that doing this is considered bad practice in general by web developers and usability experts. Jakob Nielson has this to say about removing control of the users browsing experience:

Avoid spawning multiple browser windows if at all possible — taking the "Back" button away from users can make their experience so painful that it usually far outweighs whatever benefit you're trying to provide. One common theory in favor of spawning the second window is that it keeps users from leaving your site, but ironically it may have just the opposite effect by preventing them from returning when they want to.

I believe this is the rationale for the target attribute being removed by the W3C from the XHTML 1.1 spec.

If you're dead set on taking this approach, Pim Jager's solution is good.

A nicer, more user friendly idea, would be to append a graphic to all of your external links, indicating to the user that following the link will take them externally.

You could do this with jquery:

$('a[href^="http://"]').each(function() {
    $('<img width="10px" height="10px" src="/images/skin/external.png" alt="External Link" />').appendTo(this)

});
5
  • While I mostly agree with what you're saying, I think target blank and the "rel='external'" trick do have their place, especially when you're linking to a PDF. Apr 29, 2009 at 21:52
  • rel="external" is interesting -- sitepoint.com/article/standards-compliant-world/3 -- though it looks like it needs to be used in conjunction with JavaScript to get it to work. It does allow you to avoid using the disallowed xhtml attribute "target" in-line in your html though. Thanks for mentioning it though, Mike. rel="external" is worth following. :-)
    – artlung
    Apr 29, 2009 at 22:28
  • Jimmy, what would your reasoning be for doing that when you can use a relative path? Apr 29, 2009 at 23:11
  • 1
    Reading J.Nielson's name here reminds me of bokardo.com/archives/comic-jakob-who ;-)
    – naivists
    Mar 16, 2010 at 20:21
  • I know this was posted quite a while ago, but I see the same issue happen all too often today. Someone prefaces their answer with a rant about the detrimental aspects of using the requested information, but then fails to answer the specific question that was asked. jQuery is not the same as JavaScript. Jun 16, 2018 at 11:41
6

Using jQuery:

 $('#link_other a').each(function(){
  $(this).attr('target', '_BLANK');
 });
2
  • 1
    Can't you just do: $('#link_other a').attr('target', '_blank'); ?
    – Tim Frey
    Apr 29, 2009 at 21:33
  • shorter is: $('#link_other a').attr('target', '_blank'); as artlung posted Apr 29, 2009 at 21:34
3

I use this for every external link:

window.onload = function(){
  var anchors = document.getElementsByTagName('a');
  for (var i=0; i<anchors.length; i++){
    if (anchors[i].hostname != window.location.hostname) {
        anchors[i].setAttribute('target', '_blank');
    }
  }
}
1
  • This worked perfectly for me, even with a links that have a specified class. Thanks! Oct 23, 2017 at 13:56
1

Inline:

$('#link_other').find('a').attr('target','_blank');
0

Use this for every external link

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.