I've been searching SO quite a bit for a solution like this, but I keep finding how to transfer only ONE row from one table to another, rather than appending ALL rows to table 2 from table 1 (and then clearing the rows from table 1, which is easy). Here's what I've tried so far:
function TransferRowsRight() {
var t1 = document.getElementById("t1");
const length = t1.rows.length;
for (var index = 0; index < length; index++) {
var rowHTML = $('#table1 tbody tr:first').html();
$('#table2 tr:last').after("<tr>" + rowHTML + "</tr>");
t1.deleteRow(0);
}
}
function TransferRowsLeft() {
var t2 = document.getElementById("t2");
const length = t2.rows.length;
for (var index = 0; index < length; index++) {
var rowHTML = $('#table2 tbody tr:first').html();
$('#table1 tr:last').after("<tr>" + rowHTML + "</tr>");
t2.deleteRow(0);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="display: flex; flex-direction: row">
<table id="table1" border="1">
<thead>
<tr>
<th>Food</th>
<th>Cost</th>
<th>Quantity</th>
</tr>
<tbody id="t1">
<tr>
<td>Apple</td>
<td>$0.50</td>
<td>18</td>
</tr>
<tr>
<td>Bread</td>
<td>$1.99</td>
<td>7</td>
</tr>
<tr>
<td>Salmon</td>
<td>$7.99</td>
<td>5</td>
</tr>
</tbody>
</table>
<table id="table2" border="1" style="margin-left: 2%">
<thead>
<tr>
<th>Food</th>
<th>Cost</th>
<th>Quantity</th>
</tr>
</thead>
<tbody id="t2">
<tr>
<td>Broccoli</td>
<td>$3.75</td>
<td>11</td>
</tr>
<tr>
<td>Oranges</td>
<td>$6.50</td>
<td>8</td>
</tr>
<tr>
<td>Chicken</td>
<td>$6.25</td>
<td>12</td>
</tr>
</tbody>
</table>
<div style="align-self: center">
<button onclick="TransferRowsLeft()" style="margin-left: 2%">Transfer Rows Left</button>
<button onclick="TransferRowsRight()" style="margin-left: 2%">Transfer Rows Right</button>
</div>
</div>
As you can see, my code works only for the first two transfers of rows - one left and one right - and then it doesn't work when tried for a third time. Also - and this is important - I know there has to be a much simpler and more orthodox way of doing this, like with built-in JavaScript methods, rather than what I'm doing; I just can't seem to find anything on this.