Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a newline into a pre tag (IE, Javascript)

In IE when I insert text into a <pre> tag the newlines are ignored:

<pre id="putItHere"></pre>

<script>
function putText() {
   document.getElementById("putItHere").innerHTML = "first line\nsecond line";
}
</script>

Using \r\n instead of a plain \n does not work.

<br/> does work but inserts an extra blank line in FF, which is not acceptable for my purposes.

like image 873
Itay Maman Avatar asked Oct 12 '08 11:10

Itay Maman


People also ask

Does \n work in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.

What is preformatted text in HTML?

The <pre> tag defines preformatted text. Text in a <pre> element is displayed in a fixed-width font, and the text preserves both spaces and line breaks. The text will be displayed exactly as written in the HTML source code.

Which tag is used to display pre formatted text?

The <pre> HTML element represents preformatted text which is to be presented exactly as written in the HTML file.

What is Echo Pre?

pre-echo (plural pre-echoes) An early sign or indication of something; a foreshadowing.


2 Answers

These quirksmode.org bug report and comments about innerHTML behaviour of Internet Explorer could help:

"IE applies HTML normalization to the data that is assigned to the innerHTML property. This causes incorrect display of whitespace in elements that ought to preserve formatting, such as <pre> and <textarea>."

like image 59
splattne Avatar answered Oct 16 '22 22:10

splattne


Does this work in IE?

document.getElementById("putItHere")
    .appendChild(document.createTextNode("first line\nsecond line"));

I tested it with Firefox and it works. :-)

like image 20
Chris Jester-Young Avatar answered Oct 16 '22 22:10

Chris Jester-Young