Switching the rows of an HTML table
This tutorial illustrates a number of ways to switch two rows in an HTML table using JavaScript. The techniques used here are used in the TSorter HTML table sorting function.
Ensuring a successful row swap
There are two important cases which should be considered when attempting to swap two table rows.
Consecutive Rows. The two easy cases appear when one element is directly above or below the other. Depending on the size of your table this could be very common or relatively rare.
Swapping two consecutive rows
oTable.tBodies[0].insertBefore(oRowI, oRowJ);
None-Consecutive Rows. Here we replace row j with row i saving row j to a temporary variable. Normally we could go ahead and insert the temp. row back into the table before row I, however if row I happened to be the last row of the table it will now be undefined. So we check if it is defined and then act accordingly.
Swapping two non-consecutive rows
var tmpNode = oTable.tBodies[0].replaceChild(trs[i], trs[j]);
if(typeof(trs[i]) != "undefined"){
oTable.tBodies[0].insertBefore(tmpNode, trs[i]);
}else{
oTable.appendChild(tmpNode);
}
The execution order you choose for the cases is important. If you use this in a sorting function it may be called thousands of times during a single Sort() function call. You want to make sure that the most commonly used case appears first.
Example
| ID | NAME | PRICE | LATITUDE | LONGITUDE | ADDRESS |
|---|---|---|---|---|---|
| 0 | 300 | 43.474207 | -80.588992 | 722 Cedar Bend Drive, | |
| 1 | 300 | 43.441901 | -80.584129 | 12-634 Erb St. West, | |
| 2 | 200 | 43.487166 | -80.541454 | 511 Albert Street, Waterloo, ON | |
| 3 | 450 | 43.458424 | -80.553416 | 55 McCarron Crescent, | |
| 4 | 300 | 43.440581 | -80.517814 | 128-51 Paulander Dr, |
Full code samples
Passing the numerical Row Indices and target Table ID
function exchange(i, j, tableID)
{
var table = document.getElementByID('tableID');
var trs = oTable.tBodies[0].getElementsByTagName("tr");
if(i == j+1) {
oTable.tBodies[0].insertBefore(trs[i], trs[j]);
} else if(j == i+1) {
oTable.tBodies[0].insertBefore(trs[j], trs[i]);
} else {
var tmpNode = oTable.tBodies[0].replaceChild(trs[i], trs[j]);
if(typeof(trs[i]) != "undefined") {
oTable.tBodies[0].insertBefore(tmpNode, trs[i]);
} else {
oTable.appendChild(tmpNode);
}
}
}
The above examples could be enhanced using the $() function in the Prototype JavaScript library. If you are table does not have a differentiation between header, footer or body cells then the tBodies[0] references may also be ommited.
Passing in the Row and Table Objects
function exchange(oRowI, oRowJ, oTable)
{
if(oRowI.rowIndex == oRowJ.rowIndex+1) {
oTable.insertBefore(oRowI, oRowJ);
} else if(oRowJ.rowIndex == oRowI.rowIndex+1) {
oTable.insertBefore(oRowJ, oRowI);
} else {
var tmpNode = oTable.replaceChild(oRowI, oRowJ);
if(typeof(oRowI) != "undefined") {
oTable.insertBefore(tmpNode, oRowI);
} else {
oTable.appendChild(tmpNode);
}
}
}