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

[th] row:0, cell: 0 [th] row:0, cell: 1 [th] row:0, cell: 2
[td] row:0, cell: 0 [td] row:0, cell: 1 [td] row:0, cell: 2
[td] row:1, cell: 0 [td] row:1, cell: 1 [td] row:1, cell: 2
[td] row:2, cell: 0 [td] row:2, cell: 1 [td] row:2, cell: 2

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

tableaddcolumn.js

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>

Related mredkj.com Tutorials

  1. DOM table methods
  2. DOM - Refer to table cells
  3. innerHTML vs. DOM vs. cloneNode
  4. Add rows with fade in
  5. Add rows, and submit to PHP
  6. DOM Table Add Row
  7. DOM Table Delete Row
  8. DOM Table Delete Row - includes a calendar
About this page: