Haxans web - The Internet Resource

Home|Contact Us
Home·Articles·Tutorials·Reviews·Templates·Free Stuff

Add a table row dynamically


Author: david | Posted On: 05 November 2007 | Views: 18311

 When i wrote the first function to achieve this, i faced a lot of problems specially regarding the browsers.

 The function worked flawlessly in Firefox but was throwing errors in IE. This is one of the most frustrating thing one faces in coding. After some googling and research, i soon found out the solution which i wanted to share with everyone. Yeah i know i am nice. :)

 

So here is the function:

function addNewRow(tableRef){
var myTable = document.getElementById(tableRef);
var tBody = myTable.getElementsByTagName('tbody')[0];
var newTR = document.createElement('tr');
var newTD = document.createElement('td');
newTD.innerHTML = 'This is a new row';
newTR.appendChild (newTD);
tBody.appendChild(newTR);

}

Explanation:

The variable myTable holds the reference to the table in which we want to add new TRs.

The variable tBody refers  to the tbody element which should be in each table accoring to DOM. Each table can have one tbody element. All the TRs and TDs reside in this tbody element. We might not write this when we are creating a webpage but Firefox and IE adds them on their own. 

The variable newTR contains the reference to the new created 'tr'.

Similarly newTD contains the reference to the new created 'td'.

We just added a small text into the 'td' and then appended it into the 'tr'.

append means that we attach the element into the DOM (document Object Model) so that it becomes recognizable.

Then  we append the 'tr' into the 'tbody' of that table. If we do not append the 'tr' into 'tbody' but did something like this:

myTable.appendChild(newTR);

instead, it will not work in IE 6.

 

I hope you learned something new here. This is for people like me. Not for the pros :)

Anyways, until next time.

 

Regards,

David 





Post A Comment
    Name:

Website:



© Copyright 2007 www.haxansweb.com - Haxan. All Rights Reserved. Privacy Policy.