tristen / tablesort

:arrow_up_down: A small tablesorter in plain JavaScript

Home Page:https://tristen.ca/tablesort/demo/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

running against a class results in "Element must be a table" error

adam-jones-net opened this issue · comments

I am initialising the plugin with

new Tablesort(document.getElementsByClassName('trackTable'), {
    descending: true
});

on a table that starts:

<table id="mySearchesTable" class="trackTable noSelect" cellpadding="0" cellspacing="0">

Yet I get the following error:

Uncaught Error: Element must be a table

commented

Document.getElementById(), which is the usual way of picking the table element, returns a scalar (an Element), while Document.getElementsByClassName() returns a vector (an HTMLCollection).

If you're sure you have just one element with that class, try something like:

document.getElementsByClassName('trackTable')[0]

But it's much better if you pick the element by its ID!

(Please confirm that's the issue you're having, so I can close this :)

I personally dislike using classes to enable JS. I add a data attribute to my tables
data-table-sortable or data-table-sortable="desc"
And then use a function I can call to init all tables

export function sortAllTables() {
  const sortableTables = document.querySelectorAll('[data-table-sortable]')
  if (sortableTables.length > 0) {
    sortableTables.forEach((table) => {
      // eslint-disable-next-line no-new
      let sortAsc = true
      if (table.dataset.tableSortable) {
        sortAsc = table.dataset.tableSortable === 'asc' ? false : true
      }
      new Tablesort(table, { descending: sortAsc })
    })
  }
}