I managed to fix some trouble I was having with traversing through table rows with DOM using only JavaScript but ran into 2 hurdles. I’m trying to create a table, where each row will have a set of buttons to move that particular row up, down or remove it. I was able to successfully use the .replaceChild method but it replaces the row instead of just swapping them. When I tried .moveRow, I keep getting an error saying the HTML table section does not have that method. I run into the same problem when trying to swap the current row with the row below. Any suggestions?
function up(x){
// var tableBody = document.getElementsByTagName("tbody")[0]; // tried it with tableBody and it still didn't work
var table = x.parentNode.parentNode.parentNode;
var tableRow = x.parentNode.parentNode.cloneNode(true);
var previousRow = x.parentNode.parentNode.previousSibling.cloneNode(true);
table.replaceChild(tableRow,x.parentNode.parentNode.previousSibling);
}
function down(x){
var table = x.parentNode.parentNode.parentNode;
var tableRow = x.parentNote.parentNode.cloneNode(true);
var belowRow = x.parentNode.parentNode.nextSibling.cloneNode(true);
table.moveRow(tableRow,x.parentNode.parentNode.nextSibling);
}
My buttons:
<table id="table1" border="1">
<tbody>
<tr>
<th>Column 1</th> <th>Column 2</th> <th>Column 3</th> <th>Column 4</th>
</tr>
<tr id="enterData">
<td id="buttons">
<input type="button" value="Up" onclick="up(this)" />
<input type="button" value="Down" onclick="down(this)" />
</td>
</tr>
</tbody>
</table>
You can use
insertBeforeto move up or down the rows andappendChildfor the last row, also I use *ElementSibling to avoid text node issues but that might cause compatibily issues.DEMO