3

How do I pass a target, _blank, to the js link method?

x = "my link to google"
x.link("www.google.com")

<a href="www.google.com">my link to google</a>

if its not possible is there an alternative method I could use?

JZ.
  • 21,147
  • 32
  • 115
  • 192

2 Answers2

8

You can't; the String.link method is ancient and mostly deprecated. Construct the link using DOM methods instead:

var link = document.createElement("a");
link.setAttribute("href", "http://www.google.com/");
link.setAttribute("target", "_blank");
link.appendChild(document.createTextNode("my link to google"));
...
// this, or whatever else you want to do to add it to the document:
document.getElementById("something").appendChild(link);

Either that, or just build up the string yourself. String.link isn't doing much anyway.

  • 2
    `href` and `target` are both properties of `link`. I prefer the `link.href = "http://www.google.com"` syntax over using `.setAttribute()`. But, I suppose that's just a style preference. – gilly3 Dec 08 '11 at 00:35
  • createTextNode not createTextElement – Kim T Feb 09 '17 at 20:36
0

If you really want to do it with link method you can use replace:

.replace('a href=', 'a target="_blank" href=');
noetix
  • 4,773
  • 3
  • 26
  • 47