Wednesday, May 16, 2012

building tables in IE7 with JavaScript

The documentation on this is a little old and hard to find, since IE7 is old and on rapid decline. But, for those still plagued with a significant percentage of IE7 users, please note that building tables in IE7 can require a step not required by other browsers.

We can normally build tables using HTML and omit the tbody tag without issue. Browsers are supposed to assume a single tbody when none is explicitly given. So, we may naturally assume we can do the same using the DOM methods:

var table = document.createElement('table');
var tr = document.createElement('tr');
var td = document.createElement('td');
td.innerHTML = "oh hi.";
tr.appendChild(td);
table.appendChild(tr);
document.body.appendChild(table);

And indeed, this works perfectly in Chrome, Safari, Firefox, and IE8+. However, IE7 silently adds the table to the body, but refuses to draw anything. IE7 fails to assume the tbody in this case. You need to explicitly add it, like so:

var table = document.createElement('table');
var tbody = document.createElement('tbody');
var tr = document.createElement('tr');
var td = document.createElement('td');
td.innerHTML = "oh hi.";
tr.appendChild(td);
tbody.appendChild(tr);
table.appendChild(tbody);
document.body.appendChild(table);

This will correct the issue in IE7 in without impacting other browsers. And, it'll provide a more accurate representation of the table in your script, which does include a tbody, even when not explicitly given.

2 comments: