Vikrant
Vikrant

Reputation: 101

Breaking an href text into multiple lines using javascript

I want to break the hyperlink text stored in the variable "output" into multiple lines. I current have this:

var output = "";
output = output.concat("line 1");
output = output.concat("<br />");
output = output.concat("line 2");
output = output.concat("<br />");
var a = document.createElement('a');
var linkText = document.createTextNode(output);
a.appendChild(linkText);
a.title = output;
a.href = "http://www.google.com";

Unfortunately, the text of the break tag appears, and the lines don't actually break. I've also tried "\n" instead of the break tag, but didn't work. Any recommendations? Thanks!

Upvotes: 1

Views: 192

Answers (2)

jayms
jayms

Reputation: 4018

Well createTextNode does exactly what it says. Html-code like <br> will not work here.

Either append textNodes for every line and create <br> elements in between

or simply use a.innerHTML = output;

Upvotes: 1

Wowsk
Wowsk

Reputation: 3675

Just simply put a.innerHTML = output instead of

var linkText = document.createTextNode(output);
a.appendChild(linkText);

Corrected Version:

var output = "";
output = output.concat("line 1");
output = output.concat("<br />");
output = output.concat("line 2");
output = output.concat("<br />");
var a = document.createElement('a');
a.innerHTML = output;
a.title = output;
a.href = "http://www.google.com";
document.body.appendChild(a);

Upvotes: 2

Related Questions