If I grab some html from one element, then attempt to assign it as the text content of another element, newlines are not preserved (at least not in the latest Firefox and Chromium).
So, for example, the follow code (with sensible html) produces output where the newlines are replaced by spaces. Well, except the alert, which works as expected.
$("#info").data("html", $("#info").html());
$("#jquery").text($("#info").data("html"));
document.getElementById("javascript").textContent = $("#info").data("html");
$("#alert").click(function() { alert($("#info").data("html")) });
Here's a running example: /
There should be some method of setting the html of one element as the text of another while preserving newlines properly.
Is this possible with "text" or "textContent"? Is there an alternative way to do this? Is there a simple workaround? A less than simple workaround?
If I grab some html from one element, then attempt to assign it as the text content of another element, newlines are not preserved (at least not in the latest Firefox and Chromium).
So, for example, the follow code (with sensible html) produces output where the newlines are replaced by spaces. Well, except the alert, which works as expected.
$("#info").data("html", $("#info").html());
$("#jquery").text($("#info").data("html"));
document.getElementById("javascript").textContent = $("#info").data("html");
$("#alert").click(function() { alert($("#info").data("html")) });
Here's a running example: http://jsfiddle/76S7z/2/
There should be some method of setting the html of one element as the text of another while preserving newlines properly.
Is this possible with "text" or "textContent"? Is there an alternative way to do this? Is there a simple workaround? A less than simple workaround?
br
elements? Or actual new line characters in the HTML (which are not rendered anyway). Maybe you are looking for using .html
instead of .text
to set the content. From the .text
documentation: "We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML", which is what happens with <br>
.
– Felix Kling
Commented
Jan 10, 2014 at 0:15
As you've already determined, Web browsers don't normally render newline characters \n
as line breaks. If you're resistent to adding the line break element <br />
, you can use the white-space
CSS property with the value pre-line
, which will:
Sequences of whitespace are collapsed. Lines are broken at newline characters, at
<br>
, and as necessary to fill line boxes.
Be sure to check the property's patibility tables before using.
<div style="white-space: pre-line;">
Look
at
these line breaks!
</div>
Here's a JSFiddle example.