The correct way to work with table elements in FireFox, IE and all other browsers

In my last post I talked about the differences between IE and Firefox when creating dynamic tables with the Document Object Model. Thanks to chatdor’s comment to my “Dynamic Tables In JavaScript for IE and Firefox” post, I realized that I was not paying attention to the full DOM. Perhaps many of us, like me, tend to only think of the Element object when thinking about manipulating the DOM, but there are a couple of higher level objects that derive from the Element object, the Table Element, and the Form Element, that make dealing with the more complex Elements easier. The good folks over at Mozilla have a great DOM reference which I almost always have open. So, all that being said, I would like to post some code on a better way of creating dynamic tables in JavaScript with the DOM. In the following block of code we will use createElement(’table’), to create our table but from then on we will use the Table Element’s member function insertRow and the Row’s insertCell to build the table.

var myTable = document.createElement('table');
var myRow = myTable.insertRow(-1);
var myCell = myRow.insertCell(-1);
var myTextNode = document.createTextNode('Hello World!');
myCell.appendChild(myTextNode);
In this block, I pass -1 into the insert functions to append the row or cell to the end of the rows or cells. Also in the example instead of setting the cell’s innerHTML or useing createElement(”text”) to make a text node and append, I instead use document.createTextNode, which is another case where there is a DOM function that is likely better to use than the less specific functions. By using the higher level Table object and calling functions more specific to an action the code should have better cross-browser functionality.
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • DZone
  • StumbleUpon
  • del.icio.us
  • Reddit
  • Technorati
  • Netvouz
  • Slashdot
  • blinkbits
  • blogmarks
  • Furl

This entry was posted on Wednesday, April 11th, 2007 at 11:37 am and is filed under JavaScript, FireFox, IE, DOM, tables, createElement. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response to “The correct way to work with table elements in FireFox, IE and all other browsers”

  1. Dynamic Tables In JavaScript for IE and Firefox » sweetvision says:

    […] that I was consentrating so much on the Element that I was not seeing the whole DOM. See my new post on the DOM, for a better sample for creating table elements in […]

Leave a Reply

You must be logged in to post a comment.

Bad Behavior has blocked 221 access attempts in the last 7 days.