Reputation: 11
Trying to create a table using the following code but not working. Please point out where I'm going wrong.
var i,j;
function cell(ih){
var tcell =document.createElement('td');
tcell.innerHTML=ih;
return tcell;
}
mutable=document.createElement('table');
for (i=0;i<10;i++){
row1=document.createElement('tr');
for(j=0;j<10;j++){
row1.appendChild(cell(j));
}
mutable.appendChild(row1);
document.write(mutable);
}
Upvotes: 1
Views: 543
Reputation: 12140
Also note that most times in markup, you don't see the <tbody>
element, but it is good practice to append this as a child element of the <table>
and as a parent element for all of your rows. So, your script should look more like this:
function cell(ih){
var tcell = document.createElement('td');
tcell.innerHTML = ih; // I would suggest you use document.createTextNode(ih) instead
return tcell;
}
function appendTable() { // you now have to call this function some time
mutable = document.createElement("table");
var tBody = mutable.appendChild( document.createElement("tbody") ); // technique using "fluid interfaces"
for (var i = 0; i < 10; i++) {
var row1 = tBody.appendChild( document.createElement('tr') ); // fluid interface call again
for(var j = 0; j < 10; j++) {
row1.appendChild(cell(j));
}
}
document.body.appendChild(mutable);
}
I made some style changes to your script, and I would suggest making even more, but as far as correctness, it should work.
Upvotes: 1
Reputation: 25685
You can do it by changing your script to use document.body.appendChild(mutable)
after your nested for loop:
var i,j;
function cell(ih){
var tcell =document.createElement('td');
tcell.innerHTML=ih;
return tcell;
}
mutable=document.createElement('table');
for (i=0;i<10;i++){
row1=document.createElement('tr');
for(j=0;j<10;j++){
row1.appendChild(cell(j));
}
mutable.appendChild(row1);
}
document.body.appendChild(mutable);
This appends the entire mutable
table object you've created to the <body>
element of your page. You can see it working here.
Upvotes: 1
Reputation: 944527
You have several problems, the first two are the big ones, the second two are a matter of style and risk of clashes with other code:
document.write
HTMLElementNodes. document.write only deals with strings. Grab a container element (e.g. with document.getElementById
) and append to itrow1
is a poor variable name for the row you are operating on which usually isn't the firstUpvotes: 4
Reputation: 112000
Use document.body.appendChild(...)
instead of document.write(...)
.
Upvotes: 1