Description
In the "Modifying the document" article, for the last task "Sort the table" (https://javascript.info/modifying-document#tasks) the solution given is:
let sortedRows = Array.from(table.rows)
.slice(1)
.sort((rowA, rowB) => rowA.cells[0].innerHTML > rowB.cells[0].innerHTML ? 1 : -1);
table.tBodies[0].append(...sortedRows);
Which obviously works for the table provided. But it would not work for a table with no header or with a header with more than one row, or for a table with a footer. I would like to suggest a simple change to make the solution more flexible so that it can accommodate any type of header or footer situation:
let sortedRows = Array.from(table.tBodies[0].rows)
.sort((rowA, rowB) => rowA.cells[0].innerHTML > rowB.cells[0].innerHTML ? 1 : -1);
table.tBodies[0].append(...sortedRows);
(Only code between 'Array.from('
and '.sort'
is changed). The code with table.tBodies[0]
instead of just table
is about the same length, is maybe a little easier to understand (we get the array of rows from tBodies[0]
, sort it, then write it back to the same place), and is more flexible. And it could easily be adapted to handle tables with multiple table bodies.