tristen / tablesort

:arrow_up_down: A small tablesorter in plain JavaScript
https://tristen.ca/tablesort/demo/
MIT License
1.1k stars 179 forks source link

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

Closed adam-jones-net closed 3 months ago

adam-jones-net commented 3 years ago

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

tripu commented 3 years ago

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 :)

dombarnes commented 3 months ago

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 })
    })
  }
}
tripu commented 3 months ago

(@dombarnes, a suggestion to make your code a bit more succinct)

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

Closing this as it's not an issue with Tablesort itself