views:

63

answers:

4

Hi,

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);
}
+1  A: 

Use document.body.appendChild(...) instead of document.write(...).

J-P
+4  A: 

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:

  1. You are trying to document.write HTMLElementNodes. document.write only deals with strings. Grab a container element (e.g. with document.getElementById) and append to it
  2. You are trying to document.write the entire table every time you add a row to it. Append the table once the table is complete, not every time you go through the loop.
  3. You are using globals all over the place, learn to love the var keyword
  4. row1 is a poor variable name for the row you are operating on which usually isn't the first
David Dorward
+1  A: 

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.

Pat
+1  A: 

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.

palswim