Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add target="_blank" to link with JavaScript

Tags:

javascript

I need to write a method that takes a String and parses it for links (a href). If it finds a link it should add target="_blank" to the link, if it is not already there.

Example: The Inputstring "

 <a href="www.google.com">Google</a> and <a href="www.yahoo.com"> target="_blank">Yahoo</a> are search engines

... should result in the output String

<a href="www.google.com" target="_blank">Google</a> and <a href="www.yahoo.com" target="_blank">Yahoo</a> are search engines

Any idea how to realize this?

like image 743
Paul Avatar asked Jul 25 '11 22:07

Paul


People also ask

Can you add target _blank to URL?

You can use the target="_blank" attribute if you want your users to click on a link that opens up a new browser tab. The target="_blank" attribute is used inside the opening anchor tag like this.

How do you target a link in JavaScript?

target attributes in JavaScript When a user clicks on a link, the HTML target attribute specifies in which the linked document shall open. The linked document shall open in a new tab if target=" blank" is specified with the anchor element; else, it will do so in the existing tab.

How do I add a target link?

To change the target of a link in HTML, use the target attribute of the <a>… </a> tag. The target attribute can be used to open any link in a new tab, or the same tab, etc.

What is target _blank in JavaScript?

Description. _blank. Opens the linked document in a new window or tab. _self. Opens the linked document in the same frame as it was clicked (this is default)


2 Answers

Not very difficult with plain js.

var links = document.getElementsByTagName('a');
var len = links.length;

for(var i=0; i<len; i++)
{
   links[i].target = "_blank";
}
like image 85
timw4mail Avatar answered Sep 22 '22 06:09

timw4mail


Fraught with problems but usable with plain JavaScript:

function addBlankTargets(s) {
  return (""+s).replace(/<a\s+href=/gi, '<a target="_blank" href=');
}

Or with jQuery:

function addBlankTargets(s) {
  var p = $('<p>' + s + '</p>');
  p.find('a').attr('target', '_blank');
  return p.html();
}
var s = '<a href="www.google.com">Google</a> and '
      + '<a href="www.yahoo.com">Yahoo</a> '
      + 'are search engines.';
var x = addBlankTargets(s);
x; // => '<a href="www.google.com" target="_blank">Google</a> and
   //     <a href="www.yahoo.com" target="_blank">Yahoo</a>
   //     are search engines.'
like image 37
maerics Avatar answered Sep 24 '22 06:09

maerics