18

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?

2
  • 3
    Um, I can't imagine this is the answer you're looking for, but... don't put a <div /> inside a <table />? Commented Jun 8, 2011 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: stackoverflow.com/questions/3065342/… The first answer should help you here. Commented Jun 8, 2011 at 14:48

3 Answers 3

32

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

Comments

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>

Comments

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 :)

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.