You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用:nth类伪类等指定选择器选中目标marble元素?

问题:选中指定的.marble元素(竞赛任务)

现有HTML代码如下:

<h2>Task 5</h2>
<article id="task-5">
    <div class="marble"></div>
    <div class="marble"></div>
    <section>
        <div class="marble" data-target></div>
        <div class="marble" data-target></div>
        <section>
            <div class="marble"></div>
            <div class="marble"></div>
        </section>
    </section>
</article>

需要选中带有data-target属性的.marble类div元素,但必须遵守以下规则:

  • 禁止使用以下CSS伪类/选择器:
    • :nth-child、:nth-last-child、:nth-of-type、:nth-last-of-type
    • [data-target]
    • 禁止使用+或~组合器
  • 仅允许使用单个选择器

我尝试了以下选择器,但错误选中了不带data-target的div:

#task-5 section > div:not(:last-child):not(:is(:first-child:is(:last-child)))

解决方案

使用以下选择器即可精准选中目标元素:

#task-5 > section > .marble

说明:

  • #task-5 > section 定位到article#task-5的直接子级section,排除嵌套在内部的section
  • > .marble 进一步筛选出该section下的直接子级.marble元素,正好对应带有data-target属性的那两个div
  • 完全符合规则:未使用任何禁止的伪类、选择器或组合器,且是单个选择器

内容的提问来源于stack exchange,提问作者Noah Zemljic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 19:10:50