-2

i cant understand why this code dont work on my server. I tested it on some code playgrounds with no problems...

    <!DOCTYPE html>
<html>
<head>
    <link href="design.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript">
var mylist = $('#myTable');
var listitems = mylist.find('tr');
listitems.sort(function(a, b) {
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
    </script>
</head>
<body>
<table id="myTable">
<tr>
<td>B</td>
<td>12/01/2016</td>
</tr>
<tr>
<td>A</td>
<td>12/01/2016</td>
</tr>
</table>
</body>
</html>
  • Because you try to read the table before it exists. It is like trying to eat your sandwich before it is made. You need to wait until document.ready, window.onload, or after the element is rendered. Sites like JSFiddle default the JavaScript code to run onload, not in the head like yours is. – epascarello Oct 30 '17 at 13:35

1 Answers1

2

Move your script right before the closing </body> tag or use $(document).ready() event handler.

The problem is that when your code is executed on the playground it's launched after the HTML, but when you are using your own server your current code is launched before the page is initialized.

semanser
  • 2,015
  • 2
  • 12
  • 32