Dom Table This example builds a complete 15 by 15 table. To do this manually would be very time consuming.
Study the code carefully.
First we add a tbody element with an id
Next we use nested loops to build the table rows and cells.
Finally we add the table to the document.
function maketable(){
// this creates a new tbody tag needed by ie in memory
newtablebody=document.createElement('tbody');
//add the tbody tag to the table tag
document.getElementById('buildtable').appendChild(newtablebody);
//add an id to the tbody tag
document.getElementById('buildtable').firstChild.setAttribute('id','tablebody')
for (i=1;i<=15;i++){ // now build rows and columns
newrow=document.createElement('tr');
for (j=1;j<=15;j++) {
// this creates a new td element in memory
newcell=document.createElement('td');
newtext=document.createTextNode(i*j) ; // create cell text
newcell.appendChild(newtext); // add text to cell
newrow.appendChild(newcell); //add cell to row
}
// add new row to the table
document.getElementById('tablebody').appendChild(newrow);
}
}
Next we will examine how to manipulate tag attributes using DOM programming
Exercise
Extend the program to allow the user to specify how many rows and columns the table should
have.