Paper Texture

Don't Forget <tbody>!

We all know and love the familiar table elements: <table>, <tr>, <td>, and even <th>. Over in the dustier corners of HTML, you can find the neglected children in the table family: <thead>, <tbody>, <col>, and <colgroup>. These elements are often left out, and understandably so: they're not required and add unnecessary bulk to your markup.

However, if you're doing any heavy-duty DOM scripting on a table, don't forget the <tbody>. Even if it isn't your markup, DOM-compliant browsers still consider it a child node of the <table> element (and a parent node of all descendent <tr>s). If you're assembling a table from scratch using Javascript and try to append your rows directly to the table node, Internet Explorer won't even display them.

For instance, let's say you're trying to remove a row from a table. Even if your markup looks like this:


<table id="myTable">
    <tr id="myRow">
        <td>Cell One</td>
        <td>Cell Two</td>
    </tr>
    <tr>
        <td>Cell Three</td>
        <td>Cell Four</td>
    </tr>
</table>
you still can't do this:

var table = document.getElementById("myTable");
var row = document.getElementById("myRow");

table.removeChild(row);  // raises a DOM exception
Instead, you have to account for implied <tbody> under the table. You can do this:

var table = document.getElementById("myTable");
var row = document.getElementById("myRow");
var tbody = table.getElementsByTagName("tbody")[0];

tbody.removeChild(row);           // this works

If you're not using <tbody> and <thead> in your markup at all, this might be a good reason to start. Besides provide structure to your table and additional hooks for CSS properties, it helps you avoid these occasional DOM pitfalls.

Recent Projects