title: HTML Sort Table by clicking header
body: <p>I am trying to write a script to sort a table by clicking an icon in the header, I've tried copying the code from a different website and when I copy and paste it the table sorts fine but when I apply it to my table it doesn't work. I've copied and pasted the relevant code into this link: <a href="https://codepen.io/bawsmith/pen/gOzxbyz" rel="nofollow noreferrer">https://codepen.io/bawsmith/pen/gOzxbyz</a></p>
  <pre><code>    function sortTable(n) {
    var table,
      rows,
      switching,
      i,
      x,
      y,
      shouldSwitch,
      dir,
      switchcount = 0;
    table = document.getElementById(&quot;myTable&quot;);
    switching = true;
    //Set the sorting direction to ascending:
    dir = &quot;asc&quot;;
    /*Make a loop that will continue until
    no switching has been done:*/
    while (switching) {
      //start by saying: no switching is done:
      switching = false;
      rows = table.getElementsByTagName(&quot;TR&quot;);
      /*Loop through all table rows (except the
      first, which contains table headers):*/
      for (i = 0; i &lt; rows.length - 1; i++) { //Change i=0 if you have the header th a separate table.
        //start by saying there should be no switching:
        shouldSwitch = false;
        /*Get the two elements you want to compare,
        one from current row and one from the next:*/
        x = rows[i].getElementsByTagName(&quot;TD&quot;)[n];
        y = rows[i + 1].getElementsByTagName(&quot;TD&quot;)[n];
        /*check if the two rows should switch place,
        based on the direction, asc or desc:*/
        if (dir == &quot;asc&quot;) {
          if (x.innerHTML.toLowerCase() &gt; y.innerHTML.toLowerCase()) {
            //if so, mark as a switch and break the loop:
            shouldSwitch = true;
            break;
          }
        } else if (dir == &quot;desc&quot;) {
          if (x.innerHTML.toLowerCase() &lt; y.innerHTML.toLowerCase()) {
            //if so, mark as a switch and break the loop:
            shouldSwitch = true;
            break;
          }
        }
      }
      if (shouldSwitch) {
        /*If a switch has been marked, make the switch
        and mark that a switch has been done:*/
        rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
        switching = true;
        //Each time a switch is done, increase this count by 1:
        switchcount++;
      } else {
        /*If no switching has been done AND the direction is &quot;asc&quot;,
        set the direction to &quot;desc&quot; and run the while loop again.*/
        if (switchcount == 0 &amp;&amp; dir == &quot;asc&quot;) {
          dir = &quot;desc&quot;;
          switching = true;
        }
      }
    }
  }
  </code></pre>
  <p>Any advise would be appreciated.</p>