Sunday, January 11, 2009

insertCell populates cells in reverse order with IE

WARNING: This is a departure from my usual content. I ran into a nasty little bug this afternoon while coding, and since it's not documented anywhere, I figured I would document it here.

SEVERE GEEK ALERT: Do not read unless you're a computer geek. You have been warned...

I have been using a javascript function to dynamically populate a row in an html table.

The basic formula was to create a new row to the table, and then to create 5 new cells, using:

row.insertCell(x) where x is the number of the cell.

So I had:

cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
...

And I would also assign contents to each cell.

Problem was in IE, the cells would be displayed in the order 0, 4, 3, 2, 1 but in Firefox it was 0, 1, 2, 3, 4 as expected.

What I ended up doing to resolve the problem was to create a set of cell elements like:

var cell0 = document.createElement('td');
var cell1 = document.createElement('td');
var cell2 = document.createElement('td');
....

adding all the contents to each cell, and then once the were all populated, appending them as childElements to the Row element.

row.appendChild(cell0);
row.appendChild(cell1);
row.appendChild(cell2);
...

1 comment:

  1. HAHAHAHA!

    What??

    Well, you did say, don't read unless you're a computer geek.

    Hem. Sorry. I'm sure it was a very serious sitch.

    ReplyDelete