LoginSignup
5
8

More than 1 year has passed since last update.

JavaScriptでtableタグを操作する

Last updated at Posted at 2019-06-16

DOMのtable要素には、こんなメソッドがあるという豆知識

行操作

<table>から<tr>を取得・操作する

動作 プロパティ/メソッド 戻り値
<tr>を取得 rows <tr>のHTMLコレクション
<tr>を追加 insertRow(index) 追加された<tr>
<tr>を削除 deleteRow(index) -

※index:追加時は省略可。最初は0から

セル操作

<tr>から<td>を取得・操作する

動作 プロパティ/メソッド 戻り値
<td>を取得 cells <td>のHTMLコレクション
<td>を追加 insertCell(index) 追加された<td>
<td>を削除 deleteCell(index) -

※index:追加時は省略可。最初は0から

使用例

全セルの内容を表示する
for(const tr of $table.rows){
    for(const td of tr.cells){
        console.log(td.textContent)
    }
}
縦3×横2のテーブルを作成する
for(let y=0; y<3; y++){
    const tr = $table.insertRow()
    for(let x=0; x<2; x++){
        const td = tr.insertCell()
    }
}
データからテーブルを構築する
const data = [
    [1, 2, "up", "Python", 15.42, "+3.56"],
    [2, 1, "down", "C", 14.59, "+2.03"],
    [3, 3, "", "Java", 12.40, "+1.96"],
    [4, 4, "", "C++", 10.17, "+2.81"],
    [5, 5, "", "C#", 5.59, "+0.45"],
]

for(const list of data){
    // <tbody>にもinsertRow()がある    
    $tbody.insertRow().innerHTML = list.map(v => `<td>${v}</td>`).join('')
}
テーブルの行数・列数を取得する
//行数
$table.rows.length

//列数
$table.rows[0].cells.length

//自身のインデックス番号
td.cellIndex
5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8