Create tr,td elements for a Table using JavaScript

In some situations we have to create table rows and columns dynamically.
In those cases javascript will give the better solution to create HTML elements dynamically.

we can dynamically create tr and td elements for table through javascript using document.createElement method.
Below you can find sample code to create tr and td elements for a table dynamically.


     
<html> <head> <title>Dynamically Created Table using javascript</title> <script type="text/javascript"> function AddChild() { var objtable=document.getElementById('reportbody'); var r,c; r=document.getElementById('txt1').value; c=document.getElementById('txt2').value; var i; var j; for(i=0;i<r;i++) { var elTR=document.createElement("tr"); for(j=0;j<c;j++) { var elTD1=document.createElement("td"); elTD1.style.color='red'; elTD1.style.border='1px solid #000'; elTD1.innerHTML="Test Message"; elTR.appendChild(elTD1); } elTR.style.border='3px solid black'; objtable.appendChild(elTR); } } </script> </head> <body> <div> <table id="myreport" style="border:solid 1px #000000; "> <tbody id="reportbody"> </tbody> </table> <br /> How many Rows you want to Add <input type="text" id="txt1" name="txt1" /><br /> How many Coulmns you want to Add <input type="text" id="txt2" name="txt2" /><br /> <input type="submit" id="btn_1" value="Add" onclick="AddChild();"/> </div> </body> </html>

For the above code you need to supply how many rows and how many columns you want.

I this way you can create any HTML element dynamically through javascript by supplying it's name.

I tested this with major browsers like firefox,IE ..., it works fine.
Download source code here

Recent Articles

CLR integartion in SQL Server
Create, Read and Write Files in .Net
Message Queue in .Net
Deploy Asp.Net Web Site
Queues in Vb.Net
If you have any queries or doubts post at Forum
Share on Facebook
Responses(post your response or comments below)
Name *

Email * (won't be published)

Response *