简体   繁体   中英

How to create a Html table using DOM model using javascript?

How to create a Html table using DOM model using Javascript?

for ex:

<table width="100%" border="0" cellspacing="0" cellpadding="0" id="tblMCNRoles">   
</table>

I have above table and i want to render above table like below by using DOM modal creation.

<table width="100%" border="0" cellspacing="0" cellpadding="0" id="tblMCNRoles">

<tr>
 <td bordercolor="green" align="center" valign="top" style="border-style:dotted" >
   <table width="99%" border="0" cellspacing="0" cellpadding="0" 
      class="portlet-table-body intable5"> 
      <tr><td align="center" valign="middle" class="grid6"></td></tr>
   </table>
 </td>
</tr>
</table>

I suggest you use the DOM Table methods since neither appendChild nor innerHTML are good for safe cross browser manipulation.

The DOM has insertRow and insertCell which works better.

Here is IE's documentation and here is an example from Mozillas Developer Network

<table id="table0">
 <tr>
  <td>Row 0 Cell 0</td>
  <td>Row 0 Cell 1</td>
 </tr>
</table>

<script type="text/javascript">

var table = document.getElementById('table0');
var row = table.insertRow(-1);
var cell, text;
for (var i=0; i<2; i++) {
  cell = row.insertCell(-1);
  text = 'Row ' + row.rowIndex + ' Cell ' + i;
  cell.appendChild(document.createTextNode(text));
}

</script>
var table = document.getElementById("tblMCNRoles");
var tr = document.createElement("tr");
var td = document.createElement("td");
//set attributes via setAttribute()
//add subtable via createElement and appendCHild
tr.appendChild(td);
table.appendChild(tr);

Or you can use innerHTML, but then you have to generate the HTML first

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM