Michael Plotke
Michael Plotke

Reputation: 1001

Preserving Newlines When Using ".text" or ".textContent". Possible? Alternatives? Workarounds?

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.net/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?

Upvotes: 3

Views: 4480

Answers (1)

Jacob Budin
Jacob Budin

Reputation: 10003

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 compatibility tables before using.

<div style="white-space: pre-line;">
    Look

    at
    these line breaks!
</div>

Here's a JSFiddle example.

Upvotes: 8

Related Questions