In IE when I insert text into a tag the newlines are ignored:
I've found that innerHTML is processed before it is applied to the element, hence <br> becomes a newline and multiple white spaces are removed.
To preserve the raw text you must use nodeValue, for example;
document.getElementById('pre_id').firstChild.nodeValue=' white space \r\n ad new line';
Content inside the <pre>
tag should not be considered HTML.
In fact, the point of <pre>
tag is so that it does display formatted text.
Using the innerText property is the correct way to modify the content of a <pre>
tag.
document.getElementById("putItHere").innerText = "first line\nsecond line";
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>."
Does this work in IE?
document.getElementById("putItHere")
.appendChild(document.createTextNode("first line\nsecond line"));
I tested it with Firefox and it works. :-)
The workaround can be found in the page linked to in the accepted answer. For ease of use here it is:
if (elem.tagName == "PRE" && "outerHTML" in elem)
{
elem.outerHTML = "<PRE>" + str + "</PRE>";
}
else
{
elem.innerHTML = str;
}
<br/>
shoud only output one line in all browsers. Of course remove the \n as well, code should be:
document.getElementById("putItHere").innerHTML = "first line<br/>second line";