diff --git a/2-ui/1-document/07-modifying-document/12-sort-table/solution.md b/2-ui/1-document/07-modifying-document/12-sort-table/solution.md index 62f4c92c..f40a331d 100644 --- a/2-ui/1-document/07-modifying-document/12-sort-table/solution.md +++ b/2-ui/1-document/07-modifying-document/12-sort-table/solution.md @@ -2,22 +2,18 @@ The solution is short, yet may look a bit tricky, so here I provide it with exte ```js -let sortedRows = Array.from(table.rows) // (1) - .slice(1) // (2) - .sort((rowA, rowB) => rowA.cells[0].innerHTML > rowB.cells[0].innerHTML ? 1 : -1); // (3) +let sortedRows = Array.from(table.tBodies[0].rows) // (1) + .sort((rowA, rowB) => rowA.cells[0].innerHTML > rowB.cells[0].innerHTML ? 1 : -1); // (2) -table.tBodies[0].append(...sortedRows); // (4) +table.tBodies[0].append(...sortedRows); // (3) ``` The step-by-step algorthm: -1. Get all ``, like `table.querySelectorAll('tr')`, then make an array from them, cause we need array methods. -2. The first TR (`table.rows[0]`) is actually a table header, so we take the rest by `.slice(1)`. -3. Then sort them comparing by the content of the first `` (the name field). -4. Now insert nodes in the right order by `.append(...sortedRows)`. - -Tables always have an implicit `` element, so we must insert into it as `table.tBodes[0].append(...)`: a simple `table.append(...)` would fail. +1. Get all ``, from ``. +2. Then sort them comparing by the content of the first `` (the name field). +3. Now insert nodes in the right order by `.append(...sortedRows)`. Please note: we don't have to remove row elements, just "re-insert", they leave the old place automatically. -P.S. This solution assumes that the table doesn't have multple `` (the common case). In case it does, we can modify the code accordingly: take rows only from the needed `` in step `(1)` and insert them in that `` step `(4)`. +Also note: even if the table HTML doesn't have ``, the DOM structure always has it. So we must insert elements as `table.tBodes[0].append(...)`: a simple `table.append(...)` would fail.