Languages
[Edit]
EN

JavaScript - sort HTML table by column

12 points
Created by:
maryam
1061

Result of this post:

JavaScript - sort HTML table by column (letters or numbers)

 

Code:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <style>

    table {
      	width: 100%;
    }

    table, th, td {
        border: 1px solid black;
        border-collapse: collapse;
    }

    th, td {
        padding: 5px;
        text-align: left;
    }

  </style>
</head>
<body style="height: 300px;">

  <h2>JavaScript - sort html table</h2>

  <table style="width: 500px;">
    <tr>
      <th>letters</th>
      <th>numbers</th>
    </tr>
    <tr>
      <td>ccc</td>
      <td>50</td>
    </tr>
    <tr>
      <td>bbb</td>
      <td>30</td>
    </tr>
    <tr>
      <td>aaa</td>
      <td>40</td>
    </tr>
    <tr>
      <td>eee</td>
      <td>20</td>
    </tr>
    <tr>
      <td>ddd</td>
      <td>10</td>
    </tr>
    </table>

  <div style="margin-top: 10px;">
    <button onclick="sort(0)">Sort first column (letters)</button>
    <button onclick="sort(1)">Sort second column (numbers)</button>
  </div>

  <script>

    function sort(columnIndex) {
        const table = document.querySelector('table');
        const rows = table.rows;

        outer:
        while (true) {
            for (let index = 1; index < rows.length - 1; index++) {
                const row1 = rows[index];
                const row2 = rows[index + 1];

                const text1 = row1.cells[columnIndex].innerText.toLowerCase();
                const text2 = row2.cells[columnIndex].innerText.toLowerCase();

                if (text1 > text2) {
                    row1.parentNode.insertBefore(row2, row1);
                    continue outer;
                }
            }
            break;
        }
    }

  </script>

</body>
</html>

See also

  1. Dirask - sort cross technology table

References

  1. JavaScript - compare strings or numbers
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

HTML table

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join