IE and newlines from innerHTML

I ran into a problem today that I’m surprised I haven’t run into before. Internet Explorer loses newlines when pulling text from an HTML element.

In short, if you use innerHTML, innerText or outerHTML on most elements, IE will convert newlines to spaces. Checking the charCodes of newlines (whether unix or ascii) shows them as 32s.

On the other hand, if I output (in a template) the text inside a PRE element, IE will keep the newlines. An element styled with white-space:pre won’t do the trick.

In my case, I have a TD and inner DIV which contain a text string. I need to show the full text string, with line breaks, in a popup dialog. (The CSS property white-space:pre isn’t useful, since long lines can’t wrap at all.) My two realistic options are to copy the data into a JS variable or put the text initially inside a PRE element.

Got to love Microsoft. They keep us webdevs in a job.