innerHTML, new lines and Internet Explorer

Internet Explorer (6, 7, 8) has a major anomaly with new lines handling in the innerHTML property. This problem was first reported back in 2004, and apparently seems to still affect even the latest versions of IE. On this blog post, the problem is described with these words:

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.

A first solution, proposed on Stack Overflow, consists of replacing new lines with a br element:

function txt_out(txt) {
      out_div.innerHTML += "<br />" + txt;
}

I had a similar problem in this example and with this syntax highlighter example which clearly show that the jQuery's html() method doesn't provide a cross-browser normalization of new lines.

I think that we should proceed by exclusion:

  1. What's the regular expression pattern that matches a new line with innerHTML property in IE? We should test the following patterns:
    var p1 = /\n/g;
    var p2 = /\r/g;
    var p3 = /\r\n/g;
    
    var test = document.getElementById('test').innerHTML;
    
    var patterns = [p1, p2, p3];
    
    for(var i = 0; i < patterns.length; i += 1) {
    
      alert(patterns[i].test(test));
    
    }
    
  2. If none of the above patterns matches a new line in IE, then we should consider the option of a new line replacement with a white space character (as described above). In this case we should match this replacement character and replace it with a br element.

Leave a Reply

Note: Only a member of this blog may post a comment.