Skip to content Skip to sidebar Skip to footer

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)

Solution 1:

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.

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

    at
    these line breaks!
</div>

Here's a JSFiddle example.

Post a Comment for "Preserving Newlines When Using ".text" Or ".textcontent". Possible? Alternatives? Workarounds?"