web analytics

JavaScript: build table dynamically

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

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

<code>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 comments to JavaScript: build table dynamically

  • good post anyone can easily learn through this
    thanks

  • 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

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  

  

  

Categories

A sample text widget

Etiam pulvinar consectetur dolor sed malesuada. Ut convallis euismod dolor nec pretium. Nunc ut tristique massa.

Nam sodales mi vitae dolor ullamcorper et vulputate enim accumsan. Morbi orci magna, tincidunt vitae molestie nec, molestie at mi. Nulla nulla lorem, suscipit in posuere in, interdum non magna.