Reordering the Page
When you sort a list in your script, what visitors see doesn't change. The table on the page keeps its old order. To put the page itself in a new order, the script has to move the rows.
append moves an element
You used append to add a new element at the end of another one. If the element is already on the page, append doesn't copy it: it moves it to the end.
const list = document.querySelector("#games");
const first = list.querySelector("li");
list.append(first);
The first game jumps to the end of the list. Nothing is copied, and nothing is lost.
Rows in a new order
So, to change the order of a table: sort the rows, then append each row, in the new order, to the table's body:
function byPoints(a, b) {
return Number(b.querySelector(".points").textContent) - Number(a.querySelector(".points").textContent);
}
const body = document.querySelector("#scores tbody");
const rows = Array.from(body.querySelectorAll("tr"));
rows.sort(byPoints);
for (const row of rows) {
body.append(row);
}
Step by step:
Array.from(...)turns whatquerySelectorAllgives into a real array, because only real arrays havesort;- the rows are sorted with a comparator that reads each row's cell;
- each row, in the new order, is appended to the body. The first one goes to the end, then the second one after it, and so on. When the loop ends, they are in the sorted order.
On a click
Put it in a function and give it to a button, and visitors can sort the table themselves.
Break it on purpose
Forget Array.from:
const rows = body.querySelectorAll("tr");
rows.sort(byPoints);
TypeError: rows.sort is not a function
What querySelectorAll gives looks like an array, with a length and indexes. But it isn't one, so it has no sort. Array.from makes it an array.
Mission: Sort by time
What you will see: over the flight table, a button says Sort by time. A click puts the rows of the table's body in order of departure, earliest first: SL-103, SL-101, SL-102, SL-105, SL-104.
Passengers want to see the flights in the order they leave.
- Add a button with the id
sort-by-time. - The button says
Sort by time. - A click puts the rows of the flight table's body in order of their departure time, earliest first.
- The rows themselves move: nothing is copied, and every row keeps its classes.