Packet Disarray

Despatches from longb4

Sorttable.js Not Sorting Dynamically-created Tables

At work, I’ve recently been building a web-based tool that aggregates information about network devices from a variety of sources, and allows searching based on given criteria. The js/html frontend communicates with a python backend via ajax requests. Having some experience with it in the past, I decided to use sorttable.js for sorting data by column.

Sorttable.js has an easy way to make a table sortable after dynamically adding it via DOM calls. Despite this, my table still wasn’t sorting anything when I clicked on column headers. I was adding new table rows with (paraphrased) document.getElementById('tableId').appendChild('someTrElem'), and they were showing up in the table, but none of the table headers had events listening even after calling sorttable.makeSortable.

Eventually, through exploring with my favorite DOM inspector, I discovered that all my table rows containing data had somehow been added as children of my <thead>, as opposed to the <tbody> I had also created. Once I started explicitly adding my new <tr>s to my <tbody> rather than the <table>, I was finally able to sort the table.