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

前端 未结 8 2354
一个人的身影
一个人的身影 2020-12-02 15:26

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

8条回答
  •  再見小時候
    2020-12-02 16:09

    CSS :first-child, :nth-child, and :last-child are not like :eq

    So if we had a snippet of HTML like

    Then the selector .foo:nth-child(2)will match the div #bar2. If we insert another element at the front of the container:

    Shift!

    And again we select .foo:nth-child(2), we match the div #bar1 because the 2nd child of the container also matches .foo.

    Thus, in this second example, if we try .foo:nth-child(1) or the equivalent .foo:first-child, we will not match any elements because the first child element in that container — the p tag — does not match .foo.

    Likewise, :nth-child can match children in multiple containers. In the HTML snippet:

    Shift!

    the selector .foo:last-child will match the divs #bar3 and #quux; but .foo:first-child or .foo:nth-child(1) will only match #quux because the first child of the first container is, again, not a .foo.

    Source https://content.pivotal.io/blog/css-first-child-nth-child-and-last-child-are-not-like-eq

提交回复
热议问题