Skip to content

Commit 4110f00

Browse files
committed
closes #1591
1 parent e144f39 commit 4110f00

File tree

1 file changed

+7
-11
lines changed
  • 2-ui/1-document/07-modifying-document/12-sort-table

1 file changed

+7
-11
lines changed

2-ui/1-document/07-modifying-document/12-sort-table/solution.md

+7-11
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,18 @@ The solution is short, yet may look a bit tricky, so here I provide it with exte
22

33

44
```js
5-
let sortedRows = Array.from(table.rows) // (1)
6-
.slice(1) // (2)
7-
.sort((rowA, rowB) => rowA.cells[0].innerHTML > rowB.cells[0].innerHTML ? 1 : -1); // (3)
5+
let sortedRows = Array.from(table.tBodies[0].rows) // (1)
6+
.sort((rowA, rowB) => rowA.cells[0].innerHTML > rowB.cells[0].innerHTML ? 1 : -1); // (2)
87

9-
table.tBodies[0].append(...sortedRows); // (4)
8+
table.tBodies[0].append(...sortedRows); // (3)
109
```
1110

1211
The step-by-step algorthm:
1312

14-
1. Get all `<tr>`, like `table.querySelectorAll('tr')`, then make an array from them, cause we need array methods.
15-
2. The first TR (`table.rows[0]`) is actually a table header, so we take the rest by `.slice(1)`.
16-
3. Then sort them comparing by the content of the first `<td>` (the name field).
17-
4. Now insert nodes in the right order by `.append(...sortedRows)`.
18-
19-
Tables always have an implicit `<tbody>` element, so we must insert into it as `table.tBodes[0].append(...)`: a simple `table.append(...)` would fail.
13+
1. Get all `<tr>`, from `<tbody>`.
14+
2. Then sort them comparing by the content of the first `<td>` (the name field).
15+
3. Now insert nodes in the right order by `.append(...sortedRows)`.
2016

2117
Please note: we don't have to remove row elements, just "re-insert", they leave the old place automatically.
2218

23-
P.S. This solution assumes that the table doesn't have multple `<tbody>` (the common case). In case it does, we can modify the code accordingly: take rows only from the needed `<tbody>` in step `(1)` and insert them in that `<tbody>` step `(4)`.
19+
Also note: even if the table HTML doesn't have `<tbody>`, the DOM structure always has it. So we must insert elements as `table.tBodes[0].append(...)`: a simple `table.append(...)` would fail.

0 commit comments

Comments
 (0)