简体   繁体   中英

Populate HTML Table using Javascript

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?

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>

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>

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

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