--- title: HTMLTableElement.insertRow slug: Web/API/HTMLTableElement/insertRow tags: - DOM - Gecko - Gecko DOM Reference translation_of: Web/API/HTMLTableElement/insertRow ---
insertRow は、テーブル内に新しい行を挿入します。
var row = HTMLTableElement.insertRow(index);
HTMLTableElement: HTML table 要素への参照index: 新しい行の行番号( 0 が一行目)row: 新しい行への参照が割り当てられるindex に -1 または行数に等しい場合、行は最後の行として追加される。index が省略したり、行数より大きい場合、エラーが発生する。tbody 要素が存在する場合、新しい行は最後の tbody 要素に挿入されます。var specific_tbody = document.getElementById(tbody_id);
var row = specific_tbody.insertRow(index)
<table id="TableA">
<tr>
<td>Old top row</td>
</tr>
</table>
<script type="text/javascript">
function addRow(tableID) {
// table 要素への参照を取得し、変数に代入
var tableRef = document.getElementById(tableID);
// テーブルのインデックス 0 の行(一行目)に行を挿入
var newRow = tableRef.insertRow(0);
// 一行目にセルを挿入
var newCell = newRow.insertCell(0);
// 作成したセルにテキストノードを挿入
var newText = document.createTextNode('New top row')
newCell.appendChild(newText);
}
// 引数にテーブルの id を指定して関数 addRow() を実行
addRow('TableA');
</script>
insertRow は直接テーブルに行を挿入し、新しい行への参照を返します。document.createElement() などで新たに tr 要素を作成する必要はありません。| 機能 | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| 基本サポート | 4 | 3 | 5.5 | 10.10 | 4 |
| 機能 | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| 基本サポート | {{CompatUnknown}} | {{CompatUnknown}} | {{CompatUnknown}} | {{CompatUnknown}} | {{CompatUnknown}} |
-1 となりました。