Use JavaScript and DOM to create HTML tables

Source: Internet
Author: User
<Html>
<Head>
<Title> instance code-use JavaScript and DOM to create an HTML table </title>
<Script>
Function start (){
// Obtain the body tag
Var mybody = document. getElementsByTagName ("body") [0];
// Create a <table> element and a <tbody> element
Table1 = document. createElement ("table ");
Mytablebody = document. createElement ("tbody ");
// Create all cells
MyArray = new Array ('this', 'is ', 'A', 'test ');
For (var j = 0; j <4; j ++ ){
// Create a <tr> element
Mycurrent_row = document. createElement ("tr ");
For (var I = 0; I <4; I ++ ){
// Create a <td> element-column
Mycurrent_cell = document. createElement ("td ");
// Create a text node
If (j = 0 ){
Currenttext = document. createTextNode (myArray [I]);
} Else if (I = 0 ){
Currenttext = document. createTextNode (myArray [j]);
} Else {currenttext = document. createTextNode ();
  }
Mycurrent_cell.appendChild (currenttext );
// Add the column <td> to the row <tr>
Mycurrent_row.appendChild (mycurrent_cell );
    } 
// Add the row <tr> to <tbody>
Mytablebody. appendChild (mycurrent_row );

// Add <tbody> to <table>
Table1.appendChild (mytablebody );
// Add <table> to <body>
Mybody. appendChild (table1 );
Table1.setAttribute ("border", "2 ");
Table1.setAttribute ("cellspacing", "3 ");
Table1.setAttribute ("cellpadding", "2 ");
}
</Script>
</Head>
<Body onload = "start ()">
</Body>
</Html>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.