开发者

jQuery: How to get the first “td” in all rows

I have a table, and I want get the first “td” in all rows.

My jquery here:

$("table.SimpleTable tr td:first-child").css('background-color','red');

and my HTML here:

<table class='SimpleTable' border="1" ID="Table1">
        <tr>
            <td>Left</td>
            <td>Right</td>
        </tr>
        <tr>
            <td>Left</td>
            <td>Right</td>
      开发者_如何学Python  </tr>
        <tr>
            <td>Left</td>
            <td>Right</td>
        </tr>
        <tr>
            <td>Left</td>
            <td>
                <table border="1" ID="Table2">
                    <tr>
                        <td>AAA</td>
                        <td>AAA</td>
                        <td>AAA</td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td>Left</td>
            <td>
                <table border="1" ID="Table3">
                    <tr>
                        <td>BBB</td>
                        <td>BBB</td>
                        <td>BBB</td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>

The problem here it get the first "td" in the nested table of the second "td".

Please help me!


try:

$("table.SimpleTable > tbody > tr > td:first-child").css(..);

> only searches in children instead of all descendants. we need tbody as browsers insert that into the table.

example here.


You need to select immediate/direct children, try this:

$("table.SimpleTable > tr td:first-child").css('background-color','red');

The > allows you to target only the immediate elements


Normal CSS selectors will work, you were almost spot on. First td in a nested table would be

$('table table tr td:first-child');

To limit the selection only to the second table would be:

$('table table tr td:first-child').filter(':nth(1)');

Live example at jsfiddle

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜