Hammad
Hammad

Reputation: 173

Target _blank in all Link

I've just made an html page with target _self

But now I have too many links and I want to change all link targets to _blank and it's hard for me to do. Is there is any javascript which apply on all just to write 1 time ??

Because my code is too long and it is taking too many times to change in all links. Is there is any trick?

like this

<a href="http://www.google.com"></a>
<a href="http://www.facebook.com"></a>
<a href="http://www.gmail.com"></a>
<a href="http://www.twitter.com"></a>
<a href="http://www.stackoverflow.com"></a>
<a href="http://plus.google.com"></a>

Upvotes: 17

Views: 25015

Answers (5)

Thom Wiggers
Thom Wiggers

Reputation: 7054

Put this in your <head>:

<base target="_blank">

It will make all URLs on a page open in a new page, unless target is specified.

This is a HTML5-only feature, I learned it from Google's io-2012-slides slide package.

Upvotes: 50

Matt Browne
Matt Browne

Reputation: 12419

It's pretty simple in plain JS too:

var links = document.getElementsByTagName('a');
for (var i=0, len=links.length; i < len; i++) {
  links[i].target = '_blank';
}

(Put this script right before your closing </body> tag or in any case after all the <a> tags on your page.)

Upvotes: 2

Oliver Spryn
Oliver Spryn

Reputation: 17348

To answer your question, jQuery makes this easy:

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script>
    $(function() {
        $('a[href]').attr('target', '_blank');
    });
</script>

This will not modify any <a> tags without an href attribute.

Upvotes: 8

arielnmz
arielnmz

Reputation: 9145

I've had to deal with this lots of times. Just for the record:

I think there's no need to make javascript perform this task, but here's another approach, instead you can use the find/replace function of your editor and do something like this (provided your links are in that format):

  • Open your editor and look for <a href:

    Find <a href

  • On the replace field type <atarget="_blank"href.

    Replace

  • Replace.

    Text replaced

Or you can append that to the end of the tag by looking for .com"> and replacing it for .com" target="_blank">. You can do this on all editors that have the find/replace feature. It's just a matter of finding patterns and how to replace them.

Upvotes: 2

Fr0zenFyr
Fr0zenFyr

Reputation: 1929

If you are unable to do a simple find and replace using your HTML editor, you can do something like this using jQuery:

$('a').click(function() {
  $(this).attr('target', '_blank');
});

This will automatically do a target="_blank" for every a that is clicked and open in a new window or new tab(you have no control over this, it depends on user's browser settings).

FIDDLE

Hope this helps!!

Upvotes: 1

Related Questions