JavaScript Table Sorting (Part 1 of 2) — Start Out Simple

Jason Knight
Level Up Coding
Published in
11 min readDec 10, 2020

--

There are a number of decent articles out there about doing this. In particular, Bobby Jack’s article here on Medium stands out for a few reasons:

  1. They hook the markup from the JavaScript which leaves the proper semantics alone. That’s REALLY GOOD scripting as ’tis a form of “progressive enhancement”. That means we get “graceful degradation” for users who don’t have JavaScript available or in cases — like screen/braille readeres — where it’s highly irrelevant. As much as possible when you write JavaScript you should at least TRY to make pages that are still usable for users who have scripting off/blocked/otherwise unavailable. Failing to do so basically tells large swaths of users — particularly those with accessibility needs — to go shtup themselves. This is 2020 going on 1985, accessibility violations are no joke.
  2. The markup isn’t utter garbage, in that they actually used <thead>, <tbody>, and <th>. There’s more that should go into a table than just <tr> and <td>!
  3. It leverages the fact that appendChild also removes an element’s existing place on the DOM. It’s one of the fastest ways to reorder a table is to just flat appendChild all of them. This means you don’t have to manually parentNode.removeChild() them first! It’s a very slick trick I’ve used a lot, and good to see someone else embrace.

All in all it’s a decent implementation, but like many other ways I’ve seen people do this, IMHO it has some issues as well.

  1. The example markup could be a bit more “complete” with things like SCOPE applied and using <th> for the first cell in the <tbody> rows. The problem with too many examples people put out there is incomplete markup that nubes and rubes just blindly clone. I know this is done to “simplify” things for those just learning, but in the long term it does more harm than good.
  2. It uses innerHTML which could be a risk if your table headings are user generated. InnerHTML is also slow, though in this case not so much as to be a worry. Even so innerHTML is an outdated relic you should avoid using as much as possible. It’s called the DOM, use it. NO, innerHTML is NOT DOM manipulation, no matter how many know-nothings claim otherwise.
  3. It does a lot of querySelectorAll “inside the…

--

--

Accessibility and Efficiency Consultant, Web Developer, Musician, and just general pain in the arse