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

如何使用CSS nth选择器选中第二个同名wrapper区块下的第二个container元素

实现方案

CSS原生不支持直接按元素文本内容匹配,结合你给出的DOM结构,目标元素是第二个.wrapper容器下的第二个.container子元素,可以用以下两种方式实现:

1. CSS结构匹配(推荐)

直接通过DOM层级和位置匹配元素,兼容性好,无需JS:

/* 写法1:直接匹配第二个.wrapper(不受中间br标签干扰)下的第二个.container */
.wrapper:nth-of-type(2) .container:nth-child(2) {
    background-color: gray;
    color: white;
}

说明:你原本写的.container:nth-child(n+3)会匹配所有父容器下第3位及以后的.container元素,也就是会同时选中Container 3和Container 13,不符合需求。

2. JavaScript按文本内容匹配

如果需要严格匹配文本内容,不受DOM结构变动影响,可以用JS实现:

// 遍历所有.container元素,匹配文本内容
const targetContainer = Array.from(document.querySelectorAll('.container'))
  .find(el => el.textContent.trim() === 'Container 12')

// 匹配成功后添加样式/类名
if (targetContainer) {
  targetContainer.style.cssText = 'background-color: gray;color: white;'
  // 也可以添加自定义类:targetContainer.classList.add('active')
}

内容的提问来源于stack exchange,提问作者Rodrigo Linkweb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:24:02