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.


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


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
        // 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.

Support On Demand!