17

I want to populate a predefined html table using JavaScript:

<table>
    <tr>
        <th scope="col">ID</th>
        <th scope="col">Name</th>
    </tr>
    <div id='data'/>
</table>

using

document.getElementById('data').innerHTML = ....

But since <div> is not allowed inside of <table> above code doesn't work. What is the correct way to achieve this?

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Chris
  • 8,649
  • 16
  • 55
  • 73
  • 2
    Um, I can't imagine this is the answer you're looking for, but... don't put a `
    ` inside a `
    `?
    – Domenic Jun 08 '11 at 14:38
  • I suspect that you are wanting to reference individual cells in your table rather than put 'divs' all over the place. This has been asked before on SE: http://stackoverflow.com/questions/3065342/how-do-i-iterate-through-table-rows-and-cells-in-javascript The first answer should help you here. – ʍǝɥʇɐɯ Jun 08 '11 at 14:48

3 Answers3

30

Instead of Div you can use tr and td.

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html>
<head>
<script type="text/javascript">
function addRow(content,morecontent)
{
         if (!document.getElementsByTagName) return;
         tabBody=document.getElementsByTagName("tbody").item(0);
         row=document.createElement("tr");
         cell1 = document.createElement("td");
         cell2 = document.createElement("td");
         textnode1=document.createTextNode(content);
         textnode2=document.createTextNode(morecontent);
         cell1.appendChild(textnode1);
         cell2.appendChild(textnode2);
         row.appendChild(cell1);
         row.appendChild(cell2);
         tabBody.appendChild(row);


}
</script>
</head>
<body>
<table border='1' id='mytable'>
<tbody>
<tr><td>22</td><td>333</td></tr>
<tr><td>22</td><td>333</td></tr>
</tbody>
</table>
<button onClick='addRow("123","456");return false;'>
Add Row</button>
</body>
</html>
Community
  • 1
  • 1
Kamahire
  • 2,081
  • 2
  • 19
  • 48
1

In the most basic sense:

<table>
 <tr>
  <th>ID</th>
  <th>Name</th>
 </tr>
 <tr>
  <td colspan="2">
   <div> LOTS O' CONTENT </div>
  </td>
 </tr>
</table>
josh.trow
  • 4,651
  • 19
  • 30
0

You've answered yourself - put the div in the right location - either inside the table or outside. The javascript will work, whether the div will be displayed where you'd like it to, is a different question :)

Nikoloff
  • 3,426
  • 1
  • 15
  • 18