Visit Mozilla.org

DOM:tableRow.insertCell

From MDC

« Gecko DOM Reference

Contents

[edit] Summary

Inserts a new cell into a table row and returns a reference to the cell.

[edit] Syntax

var cell = HTMLTableRowElement.insertCell(index);
  • HTMLTableRowElement is a reference to an HTML table row element.
  • index is the cell index of the new cell.
  • cell is assigned a reference to the new cell.
    If index is -1 or equal to the number of cell, the cell is appended as the last cell in the row. If index is omitted or greater than the number of rows, an error will result.

[edit] Example

<table>
  <tr id="row0">
    <td>Original cell</td>
  </tr>
</table>

<script type="text/javascript">

  function addCell(tableRowID)
  {

    // Get a reference to the tableRow
    var rowRef = document.getElementById(tableRowID);

    // Insert a cell in the row at cell index 0
    var newCell   = rowRef.insertCell(0);

    // Append a text node to the cell
    var newText  = document.createTextNode('New cell')
    newCell.appendChild(newText);
  }

// Call addCell() with the ID of a table row
addCell('row0');

</script>

To be valid in an HTML document, a TR must have at least one TD element.

Note that insertCell inserts the cell directly into the table and returns a reference to the new cell. The cell does not need to be appended separately as would be the case if document.createElement() had been used to create the new TD element.

[edit] Specification

DOM Level 2 HTML: insertCell
HTML 4.01 Table Cell: TD