Tutorials - Table Add Column with JavaScript
Add and delete columns dynamically in an HTML table
Overview
To add new rows to a table (or table section) you can use insertRow, but there isn't an equivalent insertColumn in the DOM table methods. So what you can do is iterate the rows in the table (or table section), and call insertCell for each row.
Try It
Updates
2006-11-05
- Modified
For td cells, the
insertCell
method can be used.
However, insertCell won't add th cells, so I use document.createElement('th') and appendChild.
Source
Public Domain
The HTML and JavaScript listed below are released to the public domain. Read the Terms of Use for details. The contents of this page are still copyrighted.
The JavaScript
The HTML
<form> <p> <input type="button" value="add column" onclick="addColumn('tblSample')" /> <input type="button" value="delete column" onclick="deleteColumn('tblSample')" /> </p> <table id="tblSample" border="1"> <thead> <tr> <th>[th] row:0, cell: 0</th> <th>[th] row:0, cell: 1</th> <th>[th] row:0, cell: 2</th> </tr> </thead> <tbody> <tr> <td>[td] row:0, cell: 0</td> <td>[td] row:0, cell: 1</td> <td>[td] row:0, cell: 2</td> </tr> <tr> <td>[td] row:1, cell: 0</td> <td>[td] row:1, cell: 1</td> <td>[td] row:1, cell: 2</td> </tr> <tr> <td>[td] row:2, cell: 0</td> <td>[td] row:2, cell: 1</td> <td>[td] row:2, cell: 2</td> </tr> </tbody> </table> </form>