概要
insertRow
は、テーブル内に新しい行を挿入します。
構文
var row = HTMLTableElement.insertRow(index);
HTMLTableElement
: HTML table 要素への参照index
: 新しい行の行番号( 0 が一行目)row
: 新しい行への参照が割り当てられる
index
に -1 または行数に等しい場合、行は最後の行として追加される。
index
が省略したり、行数より大きい場合、エラーが発生する。- テーブル内に既に複数の
tbody
要素が存在する場合、新しい行は最後の 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>
- HTML 文書を valid なものとするには、tr 要素か td 要素の内、少なくとも一つが必要です。
insertRow
は直接テーブルに行を挿入し、新しい行への参照を返します。document.createElement()
などで新たに tr 要素を作成する必要はありません。
ブラウザ実装状況
We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
機能 | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
基本サポート | 4 | 3 | 5.5 | 10.10 | 4 |
機能 | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
基本サポート | ? | ? | ? | ? | ? |
Gecko 固有の注意事項
- Gecko 20.0 (Firefox 20.0 / Thunderbird 20.0 / SeaMonkey 2.17) 以降では、引数 index は HTML の仕様に則り省略可能となり、初期値は
-1
となりました。