↑
Main Page
comparison function
In order to retrieve the value
Smith
from the table defined previously, you use this code:
var sSmith = colDataRows[0].cells[0].firstChild.nodeValue;
This methodology can be used to retrieve the value contained in each row, which is what you need in
order to create a comparison function for sorting.
The comparison function
The interesting thing about this comparison function is that it sorts
<tr/>
elements by using a value
contained within the row, meaning that you must retrieve that value from within the function. After
these values are retrieved, you can just use
localeCompare()
to compare them:
function compareTRs(oTR1, oTR2) {
var sValue1 = oTR1.cells[0].firstChild.nodeValue;
var sValue2 = oTR2.cells[0].firstChild.nodeValue;
return sValue1.localeCompare(sValue2);
}
This comparison function sorts the table rows by the value in the first cell (index 0). Next, you use this
comparison function with the table.
The sortTable() function
The
sortTable()
function does most of the heavy lifting. It accepts one argument, which is the ID of
the table to sort. Naturally, this means the first step in the function must be to retrieve a DOM reference
to the table as well as to locate the data rows:
function sortTable(sTableID) {
var oTable = document.getElementById(sTableID);
var oTBody = oTable.tBodies[0];
var colDataRows = oTBody.rows;
//...
}
The problem at this point is how to sort the rows in
colDataRows
. Remember,
rows
is a DOM collec-
tion, not an array and, therefore, it doesn’t have the
sort()
method. The only solution is to create an
array and fill it with the
<tr/>
elements, sort that array, and finally place the rows in order using the
DOM. So first, you iterate through the
<tr/>
elements and add them to an array:
function sortTable(sTableID) {
var oTable = document.getElementById(sTableID);
var oTBody = oTable.tBodies[0];
var colDataRows = oTBody.rows;
var aTRs = new Array;
for (var i=0; i < colDataRows.length; i++) {
aTRs.push(colDataRows[i]);
}
//...
}
371
Sorting Tables
15_579088 ch12.qxd 3/28/05 11:40 AM Page 371
Free JavaScript Editor
Ajax Editor
©
→