Html Table Javascript Add Column Dynamically

HTML Table with JavaScript – Adding a Column Dynamically

This is an example of how to add a column to an HTML table dynamically using JavaScript.

HTML

First, we need to create an HTML table with some initial data:

    
        <table id="myTable">
            <thead>
                <tr>
                    <th>Column 1</th>
                    <th>Column 2</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Row 1 - Column 1</td>
                    <td>Row 1 - Column 2</td>
                </tr>
                <tr>
                    <td>Row 2 - Column 1</td>
                    <td>Row 2 - Column 2</td>
                </tr>
            </tbody>
        </table>
    
    

JavaScript

Now, let’s add a button that will trigger the addition of a new column to the table:

    
        <button onclick="addColumn()">Add Column</button>
    
    

Next, we need to write the JavaScript code to add the column. This can be done by accessing the table element and manipulating its structure:

    
        function addColumn() {
            var table = document.getElementById("myTable"); // Get the table element
            var rows = table.getElementsByTagName("tr"); // Get all the rows
        
            // Iterate through each row and add a new cell at the end
            for (var i = 0; i < rows.length; i++) {
                var cell = rows[i].insertCell(); // Insert a new cell at the end
                cell.innerHTML = "New Column"; // Set the content of the new cell
            }
        }
    
    

When the button is clicked, the addColumn() function will be called. It finds the table element with the given ID, gets all the rows within it, and then iterates through each row to insert a new cell at the end. The content of the new cell is set to "New Column".

Output

Clicking the "Add Column" button will add a new column to the table, resulting in the following output:

Column 1 Column 2 New Column
Row 1 - Column 1 Row 1 - Column 2 New Column
Row 2 - Column 1 Row 2 - Column 2 New Column

Same cateogry post

Leave a comment