0

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>

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

There's a short tutorial on the MDC site.
@RobG That is the same link I have posted and the code from there too
0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.