HTMLTableElement.insertRow() - Web APIs 编辑

The HTMLTableElement.insertRow() method inserts a new row (<tr>) in a given <table>, and returns a reference to the new row.

If a table has multiple <tbody> elements, by default, the new row is inserted into the last <tbody>. To insert the row into a specific <tbody>:

let specific_tbody = document.getElementById(tbody_id);
let row = specific_tbody.insertRow(index)

Note: insertRow() inserts the row directly into the table. The row does not need to be appended separately as would be the case if Document.createElement() had been used to create the new <tr> element.

Syntax

var newRow = HTMLTableElement.insertRow(index);

HTMLTableElement is a reference to an HTML <table> element.

Parameters

index Optional
The row index of the new row. If index is -1 or equal to the number of rows, the row is appended as the last row. If index is greater than the number of rows, an IndexSizeError exception will result. If index is omitted it defaults to -1.

Return value

newRow is an HTMLTableRowElement that references the new row.

Example

This example uses insertRow(-1) to append a new row to a table.

We then use HTMLTableRowElement.insertCell() to insert a new cell in the new row. (To be valid HTML, a <tr> must have at least one <td> element.) Finally, we add some text to the cell using Document.createTextNode() and Node.appendChild().

HTML

<table id="my-table">
  <tr><td>Row 1</td></tr>
  <tr><td>Row 2</td></tr>
  <tr><td>Row 3</td></tr>
</table>

JavaScript

function addRow(tableID) {
  // Get a reference to the table
  let tableRef = document.getElementById(tableID);

  // Insert a row at the end of the table
  let newRow = tableRef.insertRow(-1);

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

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

// Call addRow() with the table's ID
addRow('my-table');

Result

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'HTMLTableElement.insertRow()' in that specification.
Living Standard 
Document Object Model (DOM) Level 2 HTML Specification
The definition of 'HTMLTableElement.insertRow()' in that specification.
ObsoleteSpecifies in more detail where the row is inserted.
Document Object Model (DOM) Level 1 Specification
The definition of 'HTMLTableElement.insertRow()' in that specification.
ObsoleteInitial definition

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:70 次

字数:5967

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文