nth-child and descendant selector not selecting all expected elements

为君一笑 提交于 2020-01-14 04:13:06

问题


My DOM is as follows: http://jsfiddle.net/pimvdb/AHJXk/1/.

<table>
    <tr>
        <td>
            <input type="text"><input type="text">
        </td>
        <td>
            <input type="text"><input type="text">
        </td>
    </tr>
    <tr>
        <td>
            <input type="text"><input type="text">
        </td>
        <td>
            <input type="text"><input type="text">
        </td>
    </tr>
</table>

I'm trying to select all inputs in the second td of each tr, i.e. four in total. I thought the following selector would work:

$('table tr td:nth-child(2) input')

But it only returns the first input of each second td (two in total). Why is that? If I do:

$('table tr td:nth-child(1) input')

then I do indeed get all inputs of each first td (four in total).

So why is :nth-child(2) not returning all inputs but only the first one of each matched td?


回答1:


This will get you all four of them:

$('input','table tr td:nth-child(2)')

Fiddle: http://jsfiddle.net/AHJXk/3/



来源:https://stackoverflow.com/questions/7892556/nth-child-and-descendant-selector-not-selecting-all-expected-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!