开发者

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 t开发者_开发问答able 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜