Javascript 'Element must be a table' <table id="mytable">

1.7k Views Asked by At

I am using this tablesorter: https://github.com/tristen/tablesort

However, when I view this page I'm not able to sort the columns. Chrome dev tools shows Uncaught Error: Element must be a table at new Tablesort (tablesort.js:6) at mytable.html:12

I'm assuming this table:

<table id='mytable'> 

and this code

document.getElementById('mytable')

are referencing the same 'mytable'. I've based that assumption on 'table-id' as shown here: http://tristen.ca/tablesort/demo

<!DOCTYPE html>
<html>

<head>
 <script src='./src/tablesort.js'></script>
 <script src='./src/sorts/tablesort.number.js'></script>
 <script src='./src/sorts/tablesort.date.js'></script>
 <link href='./demo/style.css' rel='stylesheet'>
 <link href='tablesort.css' rel='stylesheet'>
</head>
<body>
 <script> new Tablesort(document.getElementById('mytable')); </script>
 <table id='mytable' class="sort" border = "1">
 <thead>
 <tr>

  <th>Name</th>
  <th data-sort-method='number'>Age</th>
  <!-- <th>Age</th> -->
 </tr>
 <tr>
  <td>Ramesh Raman</td>
  <td>22</td>
 </tr>
 <tr>
  <td>Shabbir Hussein</td>
  <td>32</td>
 </tr>
 </thead>
 </table>

</body>
</html>
1

There are 1 best solutions below

1
On

It's not working because the script tag is loaded before the body. Put the code in a window.onload:

window.onload = function() {
    new Tablesort(document.getElementById('mytable'));
}

You could alternatively put the script tags at the bottom of the body, because it would be loaded last and therefore be able to find the table.