blob: f964978d40c35e2e63a355cfecc001b83fa24b7c (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
</tbody>
</table>
</div>
</div>
</body>
<script type="text/javascript">
const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;
const comparer = (idx, asc) => (a, b) => ((v1, v2) =>
v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
)(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
function doSort(th) {
console.log("Doing sort to: ", th.textContent, th)
const table = th.closest('table');
Array.from(table.querySelector('tbody').querySelectorAll('tr:nth-child(n)'))
.sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
.forEach(tr => table.querySelector('tbody').appendChild(tr) );
}
// do the work...
document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {
document.getElementsByClassName("current-sort")[0].classList.remove("current-sort");
th.classList.add("current-sort");
doSort(th);
})));
doSort(document.getElementsByClassName("current-sort")[0]);
</script>
</html>
|