...

View Full Version : Dynamically Generating A Table



Basscyst
08-17-2004, 10:35 PM
Hello,

Below is some code I'm working on just to learn to create elements using createElement and appendChild etc. My question has to do with the last line of code, it seems unnessesary but is the only way I could get the table to display. Why is that the case, I mean I'm basically telling it to take what is already there and put it there again.



<html>
<head>
<style type="text/css">
table
{
border:solid 1px;
}
</style>
<script type="text/javascript">


function makeTable()
{
var column=6;
var row=10;

var tbl=document.createElement('table');
for(i=0;i<row;i++)
{
var tr=document.createElement('tr');
tbl.appendChild(tr);
for(j=0;j<column;j++)
{
var td=document.createElement('td');
tr.appendChild(td)
td.appendChild(document.createTextNode('Hello'))
}
}
document.getElementById('tbl1').appendChild(tbl);
document.getElementById('tbl1').innerHTML=document.getElementById('tbl1').innerHTML;
}

</script>
</head>
<body onload="makeTable()">
<div id="tbl1">
</div>
</body>
</html>


Thanks,
Basscyst

Willy Duitt
08-17-2004, 11:17 PM
It could be that you are appending the table tr to soon or it could be that you forgot an important element of the table which would be the tbody....

I say I'm not sure because I made both changes (red) at the same time without thinking to do it in steps. Either way, you do need to use tbody particularly when creating tables or appending to tables using the DOM....



<html>
<head>
<style type="text/css">
table
{
border:solid 1px;
}
</style>
<script type="text/javascript">


function makeTable()
{
var column=6;
var row=10;

var tbl=document.createElement('table');
var tbody=document.createElement('tbody');
for(i=0;i<row;i++)
{
var tr=document.createElement('tr');
for(j=0;j<column;j++)
{
var td=document.createElement('td');
tr.appendChild(td)
td.appendChild(document.createTextNode('Hello'))
} tbody.appendChild(tr);
} tbl.appendChild(tbody);
document.getElementById('tbl1').appendChild(tbl);
}

</script>
</head>
<body onload="makeTable()">
<div id="tbl1">
</div>
</body>
</html>


......Willy

Basscyst
08-17-2004, 11:20 PM
Makes sense, thanks for setting me straight Willy.

Basscyst



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum