I am trying to sort a table. I’ve seen several jQuery and JavaScript solutions which do this through various means, however, haven’t seen any that use JavaScript’s native sort() method. Maybe I am wrong, but it seems to me that using sort() would be faster.
Below is my attempt, however, I am definitely missing something. Is what I am trying to do feasible, or should I abandon it? Ideally, I would like to stay away from innerHTML and jQuery. Thanks
var index = 0; //Index to sort on.
var a = document.getElementById('myTable').rows;
//sort() doesn't work on collection
var b = [];
for (var i = a.length >>> 0; i--;) {
b[i] = a[i];
}
var x_td, y_td;
b.sort(function(x, y) {
//Having to use getElementsByTagName is probably wrong
x_td = x.getElementsByTagName('td')[index].data;
y_td = y.getElementsByTagName('td')[index].data;
return x_td == y_td ? 0 : (x_td < y_td ? -1 : 1);
});
A
tdelement doesn’t have a.dataproperty.If you wanted the text content of the element, and if there’s only a single text node, then use
.firstChildbefore.data.Then when that is done, you need to append the elements to the DOM. Sorting a JavaScript Array of elements doesn’t have any impact on the DOM.
Also, instead of
getElementsByTagName("td"), you can just use.cells.If the content that you’re comparing is numeric, you should convert the strings to numbers.
If they are text strings, then you should use
.localeCompare().