While I was spotting another strange IE mis-behaviour (but I can’t reproduce it by now), I’ve wrote some code to create HTML tables with DOM manipulation (domanipulation?) that I’d like to share.

Code is heavy commented because of some IE weirdness… CSS, HTML and JavaScript are reduced to the bare minimum.

First the CSS part:

  table {
    border-collapse: collapse;
    border: 1px solid black;
  }

/* Despite having the collapse model for the
    table, IE does not support borders directly on TR.
    So we use TD */

  td {  border-bottom: 1px solid silver; }
  .odd { background-color: #D9F2AC; }
  .even { background-color: #F9F2AC; }

Here comes the HTML

<body onload="test()">
  <table>

<!-- We can't build dinamically a table starting
from the TABLE element as the outermost
parent, because Internet Explorer can't add TRs to it.
So, instead, we point out the TBODY -->

    <tbody id="theTable">
    </tbody>
  </table>
</body>

Finally, Here comes the JavaScript


/* We create 15 rows with 3 columns each */

  function test() {
    testText=document.createTextNode('This is a text for a test')
    table=document.getElementById('theTable')
    for (var i=0; i < 15; i++) {
      tr=document.createElement('TR')

/* IE does not support :hover on nothing else than A element. So,
we rely on hooking the onmouseout and onmouseover, setting the
row (this) background. Note that you should better add and
remove a class name, instead of directly modifying the style.
In some weird conditions IE will eat up a top border pixel, if you
don't (this is the bug I've tried to reproduce)
*/

      tr.onmouseover = function() { this.style.backgroundColor="green"; }
      tr.onmouseout = function() { this.style.backgroundColor=""; }
      tr.className = ((i % 2) == 0 ? 'odd': 'even')
      for (var c=0; c < 3; c++)

/* To reduce code to the minimum, you can create a
row, a td and its inner text with a line only! Note that you
NEED the cloneNode, because one textNode can be used
ONE time only...
*/

        tr.appendChild(document.createElement('TD').appendChild(testText.cloneNode(false)).parentNode)
      table.appendChild(tr)
    }
  }