1. Computing & Technology

JavaScript By Example

DOM Table: 10. Adding A Column

From , former About.com Guide

The insertCell method can not only be used with insertRow to add a new row to a table, it can also be used by itself to add a new column to a table. Again as with inserting a row where we need to make sure we add the same number of cells as there are columns, when adding a column we need to make sure that we add as many cells as there are rows.

In this example we add an extra column to the right of the existing columns in our table with the text values to be placed in that column being supplied from an array.


var tables, lastRow, row, newCell, colValues;
colValues = ['first cell','cell 2','another cell'];
tables = document.getElementsByTagName('table');
lastRow = tables[0].rows.length;
for (var i = 0.length; i < lastRow; i++) {
  row = tables[0].rows[i];
  newCell = row.insertCell(rows.cells.length);
  newCell.appendChild(document.createTextNode(colValues[i]));
}

Reader Submissions: Help Others By Providing Your Own JavaScript Examples

JavaScript By Example

©2012 About.com. All rights reserved.

A part of The New York Times Company.