1

I am trying to sort several tables using the same function within Javascript. The tables will all be similar, with me just wanting it to function that when you click on the table heading, it will sort alphabetically or in numerical order (highest to lowest), and when you click on the header again, it will sort that row in the reverse direction (e.g. lowest to highest).

I have used this code from W3 Schools: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_sort_table_desc

It works just fine for sorting just one table. However it doesn't work when I change 'GetElementById' to 'GetElementsByClassName'.

Below is my altered HTML code: Ignore the NFL content, as it's just data I'm using to test out the table contents)

<table border="1" class="supTable">
            <tr>
                <th onclick="sortTable(0)"> Team Name</th>
                <th onclick="sortTable(1)">Super Bowls</th>
            </tr>
            <tr>
                <td>Atlanta Falcons</td>
                <td>0</td>
            </tr>
            <tr>
                <td>Dallas Cowboys</td>
                <td>4</td>
            </tr>
            <tr>
                <td>Houston Texans</td>
                <td>0</td>
            </tr>
            <tr>
                <td>Green Bay Packers</td>
                <td>3</td>
            </tr>
            <tr>
                <td>New England Patriots</td>
                <td>5</td>
            </tr>
            <tr>
                <td>Oakland Raiders</td>
                <td>2</td>
            </tr>
            <tr>
                <td>New York Giants</td>
                <td>2</td>
            </tr>
            <tr>
                <td>Miami Dolphins</td>
                <td>1</td>
            </tr>
        </table>
    </div>
    <div id="supAfc">
        <table border="1" class="supTable">
            <tr> 
                <th onclick="sortTable(0)"> Team Name</th>
                <th onclick="sortTable(1)">Super Bowls</th>
            </tr>
            <tr>
                <td>Houston Texans</td>
                <td>0</td>
            </tr>
            <tr>
                <td>New England Patriots</td>
                <td>5</td>
            </tr>
            <tr>
                <td>Oakland Raiders</td>
                <td>2</td>
            </tr>
            <tr>
                <td>Miami Dolphins</td>
                <td>1</td>
            </tr>
        </table>
    </div>
    <div id="supNfc">
        <table border="1" class="supTable">
            <tr>
                <th onclick="sortTable(0)"> Team Name</th>
                <th onclick="sortTable(1)">Super Bowls</th>
            </tr>
            <tr>
                <td>Atlanta Falcons</td>
                <td>0</td>
            </tr>
            <tr>
                <td>Dallas Cowboys</td>
                <td>4</td>
            </tr>
            <tr>
                <td>Green Bay Packers</td>
                <td>3</td>
            </tr>
            <tr>
                <td>New York Giants</td>
                <td>2</td>
            </tr>
        </table>
    </div>

And this is the Javascript code:

function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;

table = document.getElementsByClassName("supTable");
switching = true;
dir = "asc"; 
while (switching) {
    switching = false;
    rows = table.getElementsByTagName("TR");
    for (i = 1; i < (rows.length - 1); i++) {
        shouldSwitch = false;
        x = rows[i].getElementsByTagName("TD")[n];
        y = rows[i + 1].getElementsByTagName("TD")[n];
        if (dir == "asc") {
            if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
            shouldSwitch= true;
            break;
            }
        } else if (dir == "desc") {
            if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
                shouldSwitch= true;
                break;
            }
        }
    }
    if (shouldSwitch) {
        rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
        switching = true;
        switchcount ++;      
    } else {
        if (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
        }
    }
}
}

I think I know why the class selector doesn't work, and am happy to try a different function if it gets me the results. Can someone please help me using Javascript and ideally not jQuery, as I'm not familiar with jQuery at the moment.

I just want to be able to use the same function on several tables, so I'm not having to copy and paste the same code lots of times and changing the Id selector each time.

EDIT - A couple of people have mentioned a different question about Query selectors. How would I use query or class selectors to correctly call/solve my problem?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
bevstar7
  • 53
  • 1
  • 1
  • 8
  • At least related if not a dupetarget: http://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method – T.J. Crowder Oct 16 '17 at 16:14
  • Missing your `
    ` before the first table. Not the answer, but you are missing it.
    – Matt Oct 16 '17 at 16:26
  • Possible duplicate of [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – Marcello B. Oct 16 '17 at 16:29
  • It's in the code. I just accidentally missed it when I copied and pasted it onto here. – bevstar7 Oct 16 '17 at 16:30
  • I don't understand why your question got downvoted without a reason. It's a perfectly valid question. – XDS Oct 16 '17 at 16:53

1 Answers1

1

I haven't tested this out. Try it out and see if it works:

 <table border="1" class="supTable1">
        <tr>
            <th onclick="sortTable('supTable1', 0)"> Team Name</th>
            <th onclick="sortTable('supTable1', 1)">Super Bowls</th>
[...]
 <div id="supAfc">
    <table border="1" class="supTable2">
        <tr> 
            <th onclick="sortTable('supTable2', 0)"> Team Name</th>
            <th onclick="sortTable('supTable2', 1)">Super Bowls</th>
        </tr>

And change the javascript function to:

 function sortTable(tableClass, n) {
     var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;

     table = document.getElementsByClassName(tableClass)[0];
     switching = true;
     dir = "asc";

(I still don't understand why your post got downvoted in the first place)

XDS
  • 3,786
  • 2
  • 36
  • 56
  • Hi thanks for the reply and trying to help. I've tried your code but it doesn't seem to work for me. Maybe I've entered it wrong. I don't know why my post got downgraded either. I literally signed up today to ask this question, and was very confused as to why someone downvoted it. – bevstar7 Oct 16 '17 at 17:32
  • I think I figured out where the problem was. getElementsByClassName returns an array. You need to pick the first element thus getElementsByClassName[0] is the right way to go. Try it out and tell me if it works. – XDS Oct 16 '17 at 18:07
  • Yeh I tried adding [0] to it, which worked, but only for the first array in the class. So if you add [0], the first table works when you sort it, but the others in the class don't. Change [0] to [1], and then the second table works, but not the others. I don't know if there's a way to call all arrays in the class at once? – bevstar7 Oct 16 '17 at 18:52
  • Make sure to change the class. Look at my code. I changed the class names of the tables 'supTable1' and 'supTable2'. Both in the class="" attribute and the invocation of the javascript functions in the click events. You have to apply all changes. – XDS Oct 16 '17 at 21:01
  • This may have solved my problem! It seems to be working now. I think I forgot to rename one of the classes. I'm going to add it to more of the tables, and then let you know if it still works. Fingers crossed. – bevstar7 Oct 16 '17 at 21:26
  • I've added it to a few tables and it's still working! Thank you very much! – bevstar7 Oct 17 '17 at 11:06