jquery - nth-child 只选择第一个元素

标签 jquery css selector

我有以下代码,我想使用 nth-child 选择特定的 class=title 但它似乎确实有效

<div class="block">
   <div class="title"></div> <!-- first title here !-->
   <div class="item"></div>
   <div class="item"></div>
   <div class="item"></div>
   <div class="title"></div> <!-- second title here !-->
   <div class="item"></div>
   <div class="title"></div> <!-- third title here !-->
   <div class="item"></div> 
   <div class="item"></div>
   <div class="item"></div>
</div>

测试 1

.title:nth-child(3){
   background-color: red;
 } 

预期结果第三个标题突出显示,但实际输出是没有突出显示

测试 2

.title:nth-child(1){
   background-color: red;
 } 

预期结果第一个标题突出显示实际输出是第一个标题突出显示

我不确定为什么它不适用于另一个 child ,而它只适用于第一个 child ..

最佳答案

如果您确实想选择类名为 .titlediv.block第三个子级,那么您必须知道 child index position 。在本例中,它是而不是。因此,您需要执行如下操作:

 .title:nth-child(7){
     background-color: red;
 } 

Working Fiddle

<小时/>

简而言之,在 div.block 中的 3 位置处没有类 title 的子级。

更新:

如果不知道子元素是否存在于指定位置,则无法使用 CSS 选择子元素。但使用 jQuery 是可能的。

$('.title:eq(2)')  //This will search for the third child with the class .title

关于jquery - nth-child 只选择第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15217303/

相关文章:

php - 完整图像而不是缩略图

javascript - 如何将 HTML 文件添加到 GitHub 存储库?

javascript - CSS视差标题和粘性导航相互排斥?

redux - Redux 选择器会导致不必要的组件渲染吗?

CSS 选择器,查找嵌套内容中的第一个出现

jQuery UI 选项卡 : Mismatching fragment identifier even with tabs defined

javascript - API请求方式

javascript - jquery/css not 选择器不起作用

javascript - jquery 和动画有多异步?

javascript - .next() jQuery 只滚动一次