第n个孩子选择错误的元素(nth-child selecting wrong element)

2019-06-26 11:53发布

对于这个特殊的网站,当我通过CSS或使用jQuery的第n个孩子的“第n个孩子”选择器捕获错误的元素。 我得到一个的孩子,我打电话之前选择:

.home article:nth-child(3) {} //captures 2nd child

这似乎是捕获的第二个孩子吧。 如果我尝试:

.home article:nth-child(1) {} //captures nothing

这捕获没有元素。 jQuery中,它显示为空数组。 下面是我工作的开发站点。 谢谢。

http://heilbrice.designliftoff.com/

Answer 1:

在你的网站,你有一个clearfix div这就是你的容器内其父元素的第一个孩子,所以你的第一article是真正的第二个孩子,不是第一次:

<div class="row-main clearfix">
    <div class="clearfix"></div>  <!-- .row-main.clearfix > :nth-child(1) -->

    <article id="post-" class=""> <!-- .row-main.clearfix > :nth-child(2) -->

在CSS中,你可以使用:nth-of-type()而不是到达第三article要素:

/* Select the 3rd article in its parent within .home */
.home article:nth-of-type(3) {}

奇怪的是, jQuery的不支持:nth-of-type()所以对于一个跨浏览器的解决方案,您必须有权选择:eq()有从零开始的索引:

// Select the 3rd article within .home
$('.home article:eq(2)')


文章来源: nth-child selecting wrong element