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/innerTe
You can concatenate the strings...
h1.innerHTML += "...I would like to insert a carriage return here...<br />";
h1.innerHTML += "Ant the other line here... <br />";
h1.innerHTML += "And so on...<br />";
jsFiddle.
I found that inserting \\n
works. I.e., you escape the escaped new line character
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);