How do I add target="_blank" to a link within a specified div?
Asked Answered
C

7

75

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?

Cullin answered 29/4, 2009 at 21:2 Comment(1)
Why not let the JavaScript detect which links are external?Macronucleus
T
154
/* 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.');
Therese answered 29/4, 2009 at 21:28 Comment(4)
He asked for javascript, not jQuery.Peccary
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') }Briannabrianne
How can we do this in react.Josselyn
Hello @AhmedShaikh please do add a new question here on Stack Overflow to ask that!Therese
N
61

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');
}
Nosography answered 29/4, 2009 at 21:8 Comment(3)
Instead of getAttributesByTagName, shouldn't it be getElementsByTagName?Monopolize
Or just linkList[i].target = '_blank';Macronucleus
This version worked like a charm for me in wordpress when adding: target="_blank" to an RSS feed with elementorPentateuch
V
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)

});
Venesection answered 29/4, 2009 at 21:26 Comment(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.Nosography
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. :-)Therese
Jimmy, what would your reasoning be for doing that when you can use a relative path?Venesection
Reading J.Nielson's name here reminds me of bokardo.com/archives/comic-jakob-who ;-)Caylor
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.Paine
M
6

Using jQuery:

 $('#link_other a').each(function(){
  $(this).attr('target', '_BLANK');
 });
Milksop answered 29/4, 2009 at 21:4 Comment(2)
Can't you just do: $('#link_other a').attr('target', '_blank'); ?Banian
shorter is: $('#link_other a').attr('target', '_blank'); as artlung postedTarpon
S
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');
    }
  }
}
Sperling answered 15/3, 2014 at 15:9 Comment(1)
This worked perfectly for me, even with a links that have a specified class. Thanks!Crabbing
I
1

Inline:

$('#link_other').find('a').attr('target','_blank');
Illyrian answered 16/3, 2010 at 20:17 Comment(0)
R
0

Use this for every external link

$('a[href^="http://"], a[href^="https://"]').attr('target', '_blank');
Reviere answered 24/9, 2013 at 12:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.