append table row in javascript code example
Example 1: javascript insert row at end of table
<table id="ThisTable">
<tr><th>Head1</th><th>Head2</th><th>Head2</th></tr>
<tr><td>Data1</td><td>Data1</td><td>Data1</td></tr>
<tr><td>Data2</td><td>Data2</td><td>Data2</td></tr>
</table>
<script>
var table = document.getElementById("ThisTable");
var row = table.insertRow(-1);
<!-- Filling the new created cell -->
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell3.innerHTML = "NEW CELL3";
</script>
Example 2: javascript append to html table tr
<table id="myTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
<tr>
<td>Row3 cell1</td>
<td>Row3 cell2</td>
</tr>
</table>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
}
</script>