jQuery

jQuery nth-child による子エレメント取得

2014年6月26日

jQuery の nth-child を利用してエレメント内に含まれる子エレメントを取得する方法です。

構文:
$(".selector:nth-child(index/even/odd/equation)")

nth-child では引数にインデックス、奇数、偶数、等間隔で子エレメントを取得することができますが、ここでは簡単にインデックス指定の例を紹介します。
例えば HTML Table があり、1列目の全エレメントを取得する場合、$("table tbody tr td:nth-child(1)") となります。

$(function () {
    $("#button1").click(function () {
        // 1列目全てのセルにテキストを追加
        $("table tbody tr td:nth-child(1)").append("<span> - 1st!</span>");
    })
});

もう少し条件を複雑にして、2列目1行目のセルのみを取得する場合、nth-child を tr と td それぞれに指定します。

$(function () {
    $("#button1").click(function () {
        // 2列目1行目のセルにテキストを追加
        $("table tbody tr:nth-child(1) td:nth-child(2)").append("<span> - target!</span>");
    })
});

例として使う HTML Table のレイアウト

<table style="width:300px; border-style:solid;" border="1">
    <tr>
        <td>1-1</td>
        <td>1-2</td>
    </tr>
    <tr>
        <td>2-1</td>
        <td>2-2</td>
    </tr>
    <tr>
        <td>3-1</td>
        <td>3-2</td>
    </tr>
</table>
<input id="button1" type="button" value="click" />

:nth-child() Selector
http://api.jquery.com/nth-child-selector/

-jQuery