function sortTable() {
var table = this.parentNode.parentNode.parentNode;
var tbody = table.querySelector("tbody");
if (!tbody) return;
var column = this.cellIndex;
var rows = tbody.rows;
var switching = true;
var direction = this.getAttribute("data-direction"); // отримати напрямок сортування
if (direction === "ascending") {
this.setAttribute("data-direction", "descending");
} else {
this.setAttribute("data-direction", "ascending");
}
while (switching) {
switching = false;
for (var i = 0; i < rows.length - 1; i++) {
var shouldSwitch = false;
var x = rows[i].getElementsByTagName("td")[column];
var y = rows[i + 1].getElementsByTagName("td")[column];
if (direction === "ascending") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
} else {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
var arrows = table.querySelectorAll(".arrow");
arrows.forEach(function (arrow) {
arrow.parentNode.removeChild(arrow);
}); // видалити всі стрілки сортування з таблиці
var arrow = document.createElement("span");
arrow.className = "arrow";
if (direction === "ascending") {
arrow.innerHTML = "▲"; // додати стрілку сортування за зростанням
} else {
arrow.innerHTML = "▼"; // додати стрілку сортування за спаданням
}
this.appendChild(arrow); // додати стрілку сортування до th
}
<table>
<thead>
<tr>
<th onclick="sortTable.call(this)">Name</th>
<th onclick="sortTable.call(this)">Age</th>
<th onclick="sortTable.call(this)">Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>25</td>
<td>USA</td>
</tr>
</tbody>
</table>