For example, there are four columns of the table:

  1. Last name
  2. First name
  3. City
  4. State

Here’s an example of how we can change the order of columns with the click of a button.

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./script.js"></script>
</head>
<body>
    <table id="table">
        <tr>
            <th>Last name</th>
            <th>First name</th>
            <th>City</th>
            <th>State</th>
        </tr>
        <tr>
            <td>Sakhuja</td>
            <td>Nikita</td>
            <td>Delhi</td>
            <td>Delhi</td>
        </tr>
        <tr>
            <td>Sakhuja</td>
            <td>Nikita</td>
            <td>Delhi</td>
            <td>Delhi</td>
        </tr>
    </table>
    <button onclick="changeOrder()">Change Order</button>
</body>
</html>

Script.js

const changeOrder = () => {
    const table = document.getElementById("table");

    const rows = table.rows;
    
    for (let i = 0; i < rows.length; i++) {
        const cells = rows[i].cells;
    
        // Get the cell to move
        const cellToMove = cells[1];
    
        // Remove the cell from its current position
        rows[i].removeChild(cellToMove);
    
        // Insert the cell into the target position
        rows[i].insertBefore(cellToMove, cells[0]);
    }
}

So when we click on the change order button, it will move the cells of each row to the target position.

Need Help With Javascript Development?

Work with our skilled Javascript developers to accelerate your project and boost its performance.

Hire JavaScript Developers

Support On Demand!

Related Q&A