JavaScriptから<table>を制御する方法
HTML要素とJavaScriptオブジェクトの対応関係
| HTML要素 |
オブジェクト |
| <table> |
Table |
| <thead> |
TableSection |
| <tbody> |
| <tfoot> |
| <tr> |
TableRow |
| <th> |
TableCell |
| <td> |
| <caption> |
HTMLElement |
テーブルを操作するメソッド
tr要素とtd要素には専用のメソッドが用意されていますが、それ以外はDocumentオブジェクトのCreateElementメソッドを使用します。
| HTML要素 |
作成 |
削除 |
| <table> |
Document.createElement( 'table' ) |
Node.remoceChild( oldChild ) |
| <tr> |
Table.insertRow() |
Table.deleteRow( index ) |
| <th> |
Document.createElement( 'th' ) |
TableRow.deleteCell( index ) |
| <td> |
TableRow.insertCell() |
テーブル (table)
テーブルの作成
var table = document.createElement( 'table' );
行 (tr)
新しい行を最後に追加
var row = table.insertRow( table.rows.length );
セル (th、td)
新しいセルを最後に追加
th要素
var th = document.createElement( 'th' );
row.appendChild( th );
td要素
var td = row.insertCell( row.cells.length );
MDN (Mozilla Developer Network) から検索