In IE when I insert text into a tag the newlines are ignored:
Here is a very small tweak to Edward Wilde's answer that preserves the attributes on the <pre> tag.
if (elem.tagName == "PRE" && "outerHTML" in elem) {
var outer = elem.outerHTML;
elem.outerHTML = outer.substring(0, outer.indexOf('>') + 1) + str + "</PRE>";
}
else {
elem.innerHTML = str;
}
I reckon this.
What I found was IE is using \r\n and Fx(others) is using \n
var newline;
if ( document.all ) newline = '\r\n';
else newline = '\n';
var data = 'firstline' + newline + 'second line';
document.getElementById("putItHere").appendChild(document.createTextNode(data));
For a TinyMCE(wysiwyg editor) plugin I once made I ended up with using BR i edit mode and cleaned it up on submit etc.
This code loops through all BR elements inside PRE elements and replaces BR with newlines.
Note that the code relies on the TinyMCE API, but can easily be written using standard Javascript.
Clean up:
var br = ed.dom.select('pre br');
for (var i = 0; i < br.length; i++) {
var nlChar;
if (tinymce.isIE)
nlChar = '\r\n';
else
nlChar = '\n';
var nl = ed.getDoc().createTextNode(nlChar);
ed.dom.insertAfter(nl, br[i]);
ed.dom.remove(br[i]);
}
Good luck!
If you don't want to use outerHTML, you can also do the following for IE, if an additional pre tag is not an issue:
if(isIE)
document.getElementById("putItHere").innerHTML = "<pre>" + content+"</pre>";
else
document.getElementById("putItHere").innerHTML = content;
if (typeof div2.innerText == 'undefined')
div2.innerHTML = value;
else
div2.innerText = value;
that worked for me.
IE9 does not normalize white spaces, unlike its predecessors.
You should test for support rather than targeting any specific browser. E.g...
var t = document.createElement(elem.tagName);
t.innerHTML = "\n";
if( t.innerHTML === "\n" ){
elem.innerHTML = str;
}
else if("outerHTML" in elem)
{
elem.outerHTML = "<"+elem.tagName+">" + str + "</"+elem.tagName+">";
}
else {
// fallback of your choice, probably do the first one.
}