tableObject.rowsコレクション

tableObject.rowsは、表(table要素)内の行(tr要素)のコレクション。

構文

$tableElementReference.rows;

$tableElementReference.rows[0]; // 表の1行目の行への参照
$tableElementReference.rows[1]; // 表の2行目の行への参照

$tableElementReference.rows.length; // 表の行数

$tableElementReference.rows[0].innerHTML; // 表の1行目の行の内容

$tableElementReference.rows[0].cells[0]; // 表の1行目の1列目のセルへの参照

サンプル

1行目1列目 1行目2列目 1行目3列目
2行目1列目 2行目2列目 2行目3列目
3行目1列目 3行目2列目 3行目3列目

サンプルの動作について

表のセルにカーソルを合わせると、そのセルの背景色を赤色にし、そのセルが所属する行の背景色を黄色にする。

サンプルのソースコード

JavaScript

<script type="text/javascript">
window.onload = function(){
    var $sampleRows = document.getElementById( "sample" ).rows;
    for ( var $rowIndex = 0; $rowIndex < $sampleRows.length; $rowIndex++ ) {
        $sampleRows[$rowIndex].onmouseover = function(){
            this.style.backgroundColor = "yellow";
        };
        $sampleRows[$rowIndex].onmouseout = function(){
            this.style.backgroundColor = "";
        };
        var $sampleCells = $sampleRows[$rowIndex].cells;
        for ( var $cellIndex = 0; $cellIndex < $sampleCells.length; $cellIndex++ ) {
            $sampleCells[$cellIndex].onmouseover = function(){
                this.style.backgroundColor = "red";
            };
            $sampleCells[$cellIndex].onmouseout = function(){
                this.style.backgroundColor = "";
            };
        }
    }
}
</script>

HTML

<table id="sample">
    <tr>
        <td>1行目1列目</td>
        <td>1行目2列目</td>
        <td>1行目3列目</td>
    </tr>
    <tr>
        <td>2行目1列目</td>
        <td>2行目2列目</td>
        <td>2行目3列目</td>
    </tr>
    <tr>
        <td>3行目1列目</td>
        <td>3行目2列目</td>
        <td>3行目3列目</td>
    </tr>
</table>

CSS

<style>
#sample {
    background-color: white;
    cursor: pointer;
}
#sample tr,
#sample td {
    background-color: inherit;
}
</style>

スポンサード リンク

カテゴリー: DOM, JavaScript, Tableオブジェクト, リファレンス パーマリンク