Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 841
Chris Avatar asked Jun 08 '11 14:06

Chris


People also ask

How do you populate a table in JavaScript?

var table = document. getElementById("myTable"); var rowNode = document. createElement("tr"); var cellNode = document. createElement("td"); var textNode = document.

How do I populate HTML table with JSON data?

The first function (get_json_data) gets the json data from the external json file. The second function (append_json) appends the data to the table. I have put comments throughout the code to explain what everything is doing. if you have any questions or if something is unclear let me know.


2 Answers

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>
like image 171
Kamahire Avatar answered Oct 08 '22 06:10

Kamahire


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>
like image 24
josh.trow Avatar answered Oct 08 '22 07:10

josh.trow