Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. HTMLTableRowElement
  4. insertCell()

HTMLTableRowElement: insertCell() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

TheinsertCell() method of theHTMLTableRowElement interface inserts a newcell (<td>) into a table row (<tr>) and returns areference to the cell.

Note:insertCell() inserts the cell directly into therow. The cell does not need to be appended separatelywithNode.appendChild() as would be the case ifDocument.createElement() had been used to create the new<td> element.

You can not useinsertCell() to create a new<th>element though.

Syntax

js
insertCell()insertCell(index)

Parameters

indexOptional

The cell index of the new cell. Ifindex is-1 or equal to the number of cells, the cell is appended as the last cell in the row. Ifindex is omitted it defaults to-1.

Return value

AnHTMLTableCellElement that references the newcell.

Exceptions

IndexSizeErrorDOMException

Thrown ifindex is greater than the number of cells.

Examples

This example usesHTMLTableRowElement.insertCell() to append a new cell to arow.

HTML

html
<table>  <thead>    <tr>      <th>C1</th>      <th>C2</th>      <th>C3</th>      <th>C4</th>      <th>C5</th>    </tr>  </thead>  <tbody>    <tr>      <td>Cell 1</td>      <td>Cell 2</td>    </tr>  </tbody></table><button>Add a cell</button><button>Remove last cell</button><div>This first row has <output>2</output> cell(s).</div>
table {  border-collapse: collapse;}th,td,table {  border: 1px solid black;}button {  margin: 1em 1em 1em 0;}

JavaScript

js
// Obtain relevant interface elementsconst bodySection = document.querySelectorAll("tbody")[0];const row = bodySection.rows[0]; // Select the first row of the body sectionconst cells = row.cells; // The collection is live, therefore always up-to-dateconst cellNumberDisplay = document.querySelectorAll("output")[0];const addButton = document.getElementById("add");const removeButton = document.getElementById("remove");function updateCellNumber() {  cellNumberDisplay.textContent = cells.length;}addButton.addEventListener("click", () => {  // Add a new cell at the end of the first row  const newCell = row.insertCell();  newCell.textContent = `Cell ${cells.length}`;  // Update the row counter  updateCellNumber();});removeButton.addEventListener("click", () => {  // Delete the row from the body  row.deleteCell(-1);  // Update the row counter  updateCellNumber();});

Result

Specifications

Specification
HTML
# dom-tr-insertcell-dev

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp