JavaScript: build table dynamically


<script type="text/javascript">
function buildTable(n_rows,n_columns) {

var the_body = document.getElementsByTagName("body")[0];

var new_table = document.createElement("table");
var new_tbody = document.createElement("tbody");

var new_row, new_col, new_text ;

for(row=1;row<=n_rows;row++) {
new_row = document.createElement("tr");
new_row.className = "tr"+row ;
for(col=1;col<=n_columns;col++) {
new_col = document.createElement("td");
new_col.className = "td"+col ;
new_text = document.createTextNode("text:" + row + ":" + col );

new_col.appendChild(new_text);
new_row.appendChild(new_col);
}
new_tbody.appendChild(new_row);
}

new_table.appendChild(new_tbody);
new_table.setAttribute("border", "2");

the_body.appendChild(new_table);

return new_table ;

}
</script>
<body>
Example:
<script type="text/javascript">
buildTable(4,3)
</script>
</body>

There is also interesting article on oreillynet.com, discussing performance improvement for such operations.

2 thoughts on “JavaScript: build table dynamically

  1. function deleteRow(){
    var tbl = document.getElementById(‘tblid’);
    var lastRow = tbl.rows.length;
    var iteration = lastRow – 1;
    //alert(iteration);
    tbl.deleteRow(iteration);
    }

    function addRow(){
    var tbl = document.getElementById(‘tblid’);
    var lastRow = tbl.rows.length;
    var iteration = lastRow;
    //var iteration = lastRow – 1;
    var row = tbl.insertRow(lastRow);

    var cell1 = row.insertCell(0);
    var element1=document.createTextNode(iteration);
    cell1.appendChild(element1);

    var cell2 = row.insertCell(1);
    var element2 = document.createElement(‘div’);
    element2.innerHTML=””;
    cell2.appendChild(element2);

    var cell3 = row.insertCell(2);
    var element3 = document.createElement(‘div’);
    element3.innerHTML=”VolvoSaabOpelAudi”;
    cell3.appendChild(element3);

    var cell9 = row.insertCell(3);
    var element9 = document.createElement(‘div’);
    element9.innerHTML=””;
    cell9.appendChild(element9);

    }
    DEMO

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.