tag bug

Internet Explorer strips leading whitespaces in text nodes

For some mysterious reason, Internet Explorer (tested in IE7 and IE8) strips leading spaces in text nodes preceded by an empty element, such as this:

<div><span></span> foo</div>

While innoccuous in static pages, it becomes problematic when DOM nodes get updated after a delay by some Javascript, as the separating whitespace has disappeared, hence ruining the layout of your text.

Surprisingly, I haven’t found any reference to this IE bug (not that there is a shortage of complaints about other IE idiosyncrasies), so I thought I’d share the problem and the solution I have found here. It’s all demonstrated in the following example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <title>IE Whitespace Bug</title>
  <script type="text/javascript">
    function fill(name) {
      var e = document.getElementById(name);
      e.innerHTML = ‘hello’;
    }
  </script>
</head>
<body onload="fill(‘hello1′); fill(‘hello2′);">
<h1><span id="hello1"></span> world</h1>
<h1><span id="hello2">&nbsp;</span> world</h1>

</body>
</html>

In the first case, the whitespace gets stripped, thus resulting in “Helloworld”. In the second example, the non-breaking space prevents IE from stripping the whitespace, so that when the span is filled by Javascript, the text reads “Hello world” as expected.

If you know other solutions or whether it’s considered a bug that will be fixed, please post in the comments!