Thursday, August 10, 2006

Tbody - the key to dynamic table generation

In the Trenches: DOM Gotchas

One day you are going to try to use document.createElement to dynamically create a table. And one day you are going to try to view this table in IE. And one day you'll notice it won't work. Then you'll you need the above post.

Lets say you have code like:

var obj = getObjectRefByID(someID);
  var tbl = document.createElement("table");
  var tr = document.createElement("tr");
  var td = document.createElement("td");
  var tn = document.createTextNode("This is a test");
  td.appendChild(tn);
  tr.appendChild(td);
  tbl.appendChild(tr);
  obj.appendChild(tbl);

It looks like it should render a table. But it won't.

The secret? You need to have a tbody tag around the content of the table.

On a related note, I got so tired of writing code like the above, that I wrote a wrapper that allows me to write:

 var elt = $E('table', {border: 1},
             $E('tbody', {},
              $E('tr', {},
               $E('td', {}, "Column 1"),
               $E('td', {}, "Column 2"))));

I find that much easier to read and follow as it follows the same shape as the underlying HTML.

This isn't new of original of course - the notation is very Lisp like, and the $E naming convention is inspired by prototype.

Update: Bonus tip. If you want to take advantage of rowspan and colspan in your dynamic tables, make sure you use the right case:

   tdNode.setAttribute("rowSpan", 2); // rowspan will be ignored
   tdNode.setAttribute("colSpan", 4); // colspan will be ignored

Ahhh, the joys of cross browser development.

No comments:

Post a Comment