.rows[] and .cells[] in IE when using cloneNode()

by @jehiah on 2005-09-21 21:36
Filed under: All, HTML, IE, Javascript

There are a set of accessors specific to tables which make it easy to manipulate them using Javascript. But they are only available when the node is part of the document tree.

Those accessors are .tbodies[], .rows[], .cells[]. Normally you use .childNodes[] and .firstChild and such when manipulating the javascript DOM tree. But the others seem simpler. A good background on these functions is available at http://www.quirksmode.org/dom/w3c_html.html.

One use for these accessors is an easy way to duplicate rows in a table using the cloneNode(true) function. (passing in 'true' forces a deep copy).

This works like so:

[js]
function duplicateRow(){
   table = document.getElementById("tableID");
   var newRow = table.tBodies[0].rows[0].cloneNode(true);
    //modify newRow as appropriate
   table.tBodies[0].appendChild(newRow);
}
[/js]

All works well until you try to modify the variable newRow using the .cells[] notation.

The following code breaks in IE (it works of course in FireFox).

[js]
function duplicateRow(){
   table = document.getElementById("tableID");
   var newRow = table.tBodies[0].rows[0].cloneNode(true);
   newRow.cells[0].innerHTML = "cell 1 content";
   newRow.cells[1].innerHTML = "cell 2 content";
   table.tbodies[0].appendChild(newRow);
}
[/js]

It turns out that the .cells[] accessor is only available after you append the row into the DOM tree. The nice thing about .cells[] is it ignores text nodes that you have to work around when using .childNodes. Apparently deep copy has some other meaning in IE.

The Solution : Append first, access later

[js]
function duplicateRow(){
   table = document.getElementById("tableID");
   var newRow = table.tBodies[0].rows[0].cloneNode(true);
   table.tBodies[0].appendChild(newRow);
   newRow.cells[0].innerHTML = "cell 1 content";
   newRow.cells[1].innerHTML = "cell 2 content";
}
[/js]
Subscribe via RSS ı Email
© 2016 - Jehiah Czebotar