【发布时间】:2020-11-04 18:17:39
【问题描述】:
除了包含在
.toc-excluded
我试过了
const headings = document.querySelectorAll(
".article--full :not(.toc-excluded) h2, .article--full :not(.toc-excluded) h3"
);
headings.forEach(hd => hd.classList.add("red"))
.red {
color: red;
}
<div class='article--full'>
<div>many divs in between</div>
<div class='toc-excluded'>
<div>many divs in between</div>
<h2>h2</h2>
<h3>h3</h3>
</div>
<div>many divs in between</div>
<div class='manyotherdivs'><h2>h2</h2></div>
<div class='manyotherdivs'><h3>h3</h3></div>
</div>
【问题讨论】:
-
我给你做了minimal reproducible example你也可以这样做
-
我不知道 CSS 选择器是否能够单独执行此操作。它不是为这种场景设计的。您可能只需要获取所有 h2/h3 并在代码中检查它们的父级
-
您当前的代码 sn-p 似乎可以正常工作。它被编辑了几次,这仍然准确地描述了你的场景吗?
-
@3limin4t0r 当前的 sn-p 选择最后两个 H* 元素,我已经理解了这个问题,前两个 h* 元素应该从 NodeList 中排除,即除第一个之外的所有元素两个 H*s 应该显示为红色。
-
@Teemu 我不太明白。它似乎依赖于介于两者之间的一些 div。为什么 .toc 排除的 h3 未在此处排除 codepen.io/matoeil/pen/eYJLPjP ?