Sorting HTML Tables with JavaScript
Many developers seek JavaScript solutions for sorting tables. A simple and effective solution is to sort each column alphabetically. This solution suits the need to disregard code, numbers, or currency and focus on the text.
Solution Overview
This solution involves adding a click event to each header cell. For the respective table, it locates all rows (except the first) and sorts them based on the clicked column's value. Once sorted, it re-inserts the rows into the table in the new order.
Implementation Details
Code Example in JavaScript and HTML
<code class="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)); // Event Handling document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => { 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) ); })));</code>
<code class="html"><table> <tr><th>Country</th><th>Date</th><th>Size</th></tr> <tr><td>France</td><td>2001-01-01</td><td>25</td></tr> <tr><td>spain</td><td>2005-05-05</td><td></td></tr> <tr><td>Lebanon</td><td>2002-02-02</td><td>-17</td></tr> <tr><td>Argentina</td><td>2005-04-04</td><td>100</td></tr> <tr><td>USA</td><td></td><td>-6</td></tr> </table></code>
This solution efficiently sorts HTML tables alphabetically with a single click on the column header, without any external dependencies. Its simplicity and compatibility with major browsers make it a suitable option for many sorting needs.
The above is the detailed content of How to Sort HTML Tables Alphabetically with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!