jQuery difference between :eq() and :nth-child()

2019-01-13 10:19发布

In jQuery, what are some of the key differences between using :eq() and :nth-child() to select any elements ?

Also in general, for the starting index, in which case does it start from "0" and when it starts from "1" ?

8条回答
走好不送
2楼-- · 2019-01-13 11:21

nth-child selects the nth child of parent object(s) other selects n-th element in a collection (index starting from 0 or 1 is only a trivial part the difference). so saying tr td:nth-child(5) selects every tr and gets their 5th children where as eq gets all tds in all trs and selects only 5th td ... The main difference is that. Indeed the wording of the documentation does not point out that fact straight but garbles the words like it is black magic ...

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-13 11:22
$("#dataTable tr:nth-child(1) td:nth-child(2)").html();

here dataTable is a table

<table id="dataTable" width="50%">
    <thead>
        <th>Name</th>
        <th>EnrollNo.</th>
    </thead>
    <tbody>
        <tr>
           <td>Somdip</td><td>IT001<td>
        </tr>
        <tr>
           <td>Sanyal</td><td>IT002<td>
        </tr>
    </tbody>
</table>

The nth-child selector of jquery will help you to fetch the exact cell values from this table. A practical example where tr:nth-child(1) td:nth-child(2) fetches the 1,2 cell of the table.

查看更多
登录 后发表回答