How can I insert new line/carriage returns into an element.textContent?

user1236489 picture user1236489 · Apr 2, 2012 · Viewed 224.7k times · Source

As silly as it may sound, I still haven't found an appropriate answer.

Let's say I want to dynamically create a new DOM element and fill up its textContent/innerText with a JS string literal.
The string is so long I would like to split it into three chunks:

var h1 = document.createElement("h1");

h1.textContent = "This is a very long string and I would like to insert a carriage return HERE...
moreover, I would like to insert another carriage return HERE... 
so this text will display in a new line";

The problem is, if i write

h1.textContent = "...I would like to insert a carriage return here... \n";

it doesn't work, probably because the browser considers the '\n' to be pure text and displays it as such (the \r doesn't work either).

On the other hand, I could change the h1.innerHTML instead of the textContent and write:

h1.innerHTML = "...I would like to insert a carriage return here...<br />";

Here the <br /> would do the job, but doing so would replace not just the text content but all the HTML content of my h1, which is not quite what I want.

Is there a simple way to solve my problem?
I wouldn't resort to creating multiple block elements just to have the text on different lines.
Any idea would be greatly appreciated.
Thanks in advance.

Answer

nelek picture nelek · Oct 10, 2015

I know this question posted long time ago.

I had similar problem few days ago, passing value from web service in json format and place it in table cell contentText.

Because value is passed in format, for example, "text row1\r\ntext row2" and so on.

For new line in textContent You have to use \r\n and, finally, I had to use css white-space: pre-line; (Text will wrap when necessary, and on line breaks) and everything goes fine.

Or, You can use only white-space: pre; and then text will wrap only on line breaks (in this case \r\n).

So, there is example how to solve it with wrapping text only on line breaks :

var h1 = document.createElement("h1");

//setting this css style solving problem with new line in textContent
h1.setAttribute('style', 'white-space: pre;');

//add \r\n in text everywhere You want for line-break (new line)
h1.textContent = "This is a very long string and I would like to insert a carriage return \r\n...";
h1.textContent += "moreover, I would like to insert another carriage return \r\n...";
h1.textContent += "so this text will display in a new line";

document.body.appendChild(h1);