Apr/071
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.
1
2
3
4
5 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.
Enjoy this article?
Sorry, the comment form is closed at this time.