I'm using Nick Grealy's amazingly terse table sorter (Sorting HTML table with JavaScript), and trying to modify it to show a triangle to indicate which column is sorted. I assign a class to the <th> in question, but the triangle doesn't appear. Curiously, if I assign an ID to the then I can get the triangle to appear, but if there's more than one table on the page, then multiple tables can't contain a <th> with the same ID, so only one table will show the sort triangle.
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));
// do the work...
oldTH = document; // Prime the th variable to avoid undefined error
document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {
oldTH.id = '';
th.id = 'downArrow';
th.class = 'downArrow';
oldTH = th;
const table = th.closest('table');
Array.from(table.querySelectorAll('tr:nth-child(n+2)'))
.sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
.forEach(tr => table.appendChild(tr) );
})));
table, th, td {
border: 1px solid black;
margin-bottom: 12px;
}
th {
cursor: pointer;
}
#downArrow::after { content: '▼'; color: green; }
.downArrow::after { content: '▼'; color: green; }
<table>
<tr><th>Country</th><th>Date</th><th>Size</th></tr>
<tr><td>France</td><td>2001-01-01</td><td><i>25</i></td></tr>
<tr><td><a href=#>spain</a></td><td><i>2005-05-05</i></td><td></td></tr>
<tr><td><b>Lebanon</b></td><td><a href=#>2002-02-02</a></td><td><b>-17</b></td></tr>
<tr><td><i>Argentina</i></td><td>2005-04-04</td><td><a href=#>100</a></td></tr>
<tr><td>USA</td><td></td><td>-6</td></tr>
</table>
<table>
<tr><th>Country</th><th>Date</th><th>Size</th></tr>
<tr><td>France</td><td>2001-01-01</td><td><i>25</i></td></tr>
<tr><td><a href=#>spain</a></td><td><i>2005-05-05</i></td><td></td></tr>
</table>