All in the <head> – Ponderings and code by Drew McLellan –

Page Manipulation with W3C DOM

I don’t know if you’re familiar with the rhyme about the old lady who swallowed a fly, but after a brief exercise in manipulating an XHTML table using the W3C DOM, I have great sympathy for that old lady’s plight. The task was simple – on click of a link, insert a new row at the bottom of the table. The row was to have two cells, a TH heading cell and a TD data cell. The heading cell needed to contain a label, and the data cell an input box. I really couldn’t have simplified it much if I was merely building a test case. The process goes something like this.

Each element you need to insert has to be constructed as a new object. This means that the row, the header cell, the data cell and their contents all have to be created as new objects in the document. Example:

var row = document.createElement(‘tr’);
var head = document.createElement(‘th’);
var data = document.createElement(‘td’);

You carry on like this until each element has been created. Even the text that needs to exist inside the label has to be created as a text node – you have to create every damn thing down to the finest level. Then comes the old-lady-who-swallowed-a-fly bit. You have to start and the bottom and append each item to the item that has to contain it. It’s simultaneously tedious and mind-boggling.

data.appendChild(field); label.appendChild(labeltext); head.appendChild(label); row.appendChild(head); row.appendChild(data);

Then the whole lot has to be appended to the table.

table.appendChild(row);

So all in all I’ve written 30 lines of code to add a two-cell row to a table, I’ve swallowed the spider to catch the fly, and then I figure out that the methods I’ve used are DOM Level 2 and therefore are only supported by Mozilla-based browsers. So, I’m going to do it at the server instead.

She’s dead, of course.