JavaScript - sort HTML table by column

12 points
Created by:

Result of this post:

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



// ONLINE-RUNNER:browser;

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

    table {
      	width: 100%;

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

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

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

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

  <table style="width: 500px;">

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


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

        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;



See also

  1. Dirask - sort cross technology table


  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.

❤️💻 🙂