Tuesday, October 03, 2006

Using table.insertRow(): A word of advice

Only if I knew, I would have saved myself some countless hours of frustration…

Via JavaScript, you have an easy method of dynamically creating tables. The object representing the element has methods that easily helps in appending rows and cells. For example, lets say I have a variable otbody that is referencing the element, creating a row with three cells will be:

otbody.insertRow (0); //this creates the first row
otbody.rows[0].insertCell(0); //this makes adding cells possible
otbody.rows[0].cells[0].appendChild(document.createTextNode(‘Firstcell’));//populates the first cell
otbody.rows[0].cells[1].appendChild(document.createTextNode(‘Secondcell’));//populates the second cell
otbody.rows[0].cells[2].appendChild(document.createTextNode(‘Thirdcell’));//populates the third cell

What I did not know, which led to me wasting a lot of time, is that for this above code to work, the [otbody] object must be a child of the [table] object. What I did, which came out to be wrong, was that I attached the [otbody] to a [documentFragment] object and then append the [documentFragment] object to the [otable] object. I wanted a way of bunching the table’s content together so as to facilitate easy removal that was why I appended it to a [documentFragment] object; but that was wrong.

So to make the above code work, somewhere earlier in the source codes, I would have to include this:


No comments: