1. Computing & Technology

JavaScript By Example

DOM Table: 9. Adding A Row

From , former About.com Guide

We can use the insertRow and insertCell methods to add a new row to an existing table without having to write overly complex code involving lots of createElement calls. he main thing you do need to watch for when adding a new row into a table is that you must create the correct number of cells to make the row complete. The number of cells to create may be complicated by any cells in the table that span multiple columns where the number of cells in that row is therefore less than the total number of columns in the table.

In this example we add a new row to the end of the first table on the page with each cell in the new row to contain text. The rowValues array defines the text that each of the cells will contain and so we need to make sure that the array contains as many entries as there are columns in the table.


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

Related Searches insertrow cells nbsp array span lt

©2012 About.com. All rights reserved.

A part of The New York Times Company.