03 Feb

possible bug in DOM-based table generation

I spent half an hour or more hunting down this bug.

If you want to create a table in JavaScript such that it

appearslike
this…

…it is not as simple as the following might suggest:

 var table=document.createElement('table');
 var row=table.insertRow(0);
 var cell=row.insertCell(0); cell.rowSpan=2; cell.appendChild(document.createTextNode('appears'));
 cell=row.insertCell(1); cell.appendChild(document.createTextNode('like'));
 row=table.insertRow(1);
 cell=row.insertCell(0); cell.appendChild(document.createTextNode('this...'));
 document.getElementsByTagName('body')[0].appendChild(table);

The problem is that the colSpan in the first cell pushes the cell into two rows, but there is only one row in existance in the table.

It’s an annoyance, and the workaround is also annoying.

To properly build the table, you need to stretch the cell downwards as you add rows:

 var table=document.createElement('table');
 var row=table.insertRow(0);
 var stretchycell=row.insertCell(0); stretchycell.appendChild(document.createTextNode('appears'));
 var cell=row.insertCell(1); cell.appendChild(document.createTextNode('like'));
 row=table.insertRow(1); stretchycell.rowSpan=2;
 cell=row.insertCell(0); cell.appendChild(document.createTextNode('this...'));
 document.getElementsByTagName('body')[0].appendChild(table);

If I’m wrong, and there is a simpler way to do this, then please enlighten me – it’s annoying.