How to dynamically add a new column to an HTML table with JavaScript?

Sometimes, we want to dynamically add a new column to an HTML table with JavaScript.

In this article, we’ll look at how to dynamically add a new column to an HTML table with JavaScript.

How to dynamically add a new column to an HTML table with JavaScript?

To dynamically add a new column to an HTML table with JavaScript, we can loop through each row and add td elements into them.

For instance, we write:

<table id="table">
  <tr>
    <th><input type="text" value="test 1" /></th>
  </tr>
  <tr>
    <td><input type="text" value="test 2" /></td>
  </tr>
</table>

<button type="button">add column</button>

to add a table with an add column button.

Then we write:

const addColumn = () => {
  for (const [i, row] of [...document.querySelectorAll('#table tr')].entries()) {
    const input = document.createElement("input")
    input.setAttribute('type', 'text')
    const cell = document.createElement(i ? "td" : "th")
    cell.appendChild(input)
    row.appendChild(cell)
  };
}

document.querySelector('button').onclick = addColumn

to add the addColumn function and assign that as the click handler of the button.

In addColumn, we loop through each row with a for-of loop.

In the loop block, we create an input and set the type attribute of it with:

const input = document.createElement("input")
input.setAttribute('type', 'text')

Then we create a new table cell with:

const cell = document.createElement(i ? "td" : "th")

Next, we add the input into the cell with:

cell.appendChild(input)

Finally, we add the column cell to the row with:

row.appendChild(cell)

And we repeat this for the other rows.

Now when we click on the add column button, we see a new column added.

Conclusion

To dynamically add a new column to an HTML table with JavaScript, we can loop through each row and add td elements into them.