如何在 "pure" JS 中 Select 没有父 Class 的元素?
How to Select Element That Does Not have parent Class in "pure" JS?
我如何包含 DOM 结构中的所有 .article-full h2
和 .article-full h3
,但包含在中的 h2 和 h3 除外
.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>
:not
的所有语法还没有完全支持,因此最好还是依赖旧的好 JS。正如 Liam 所建议的,您必须过滤要从列表中排除的元素,如下所示:
const headings = Array.from(
document.querySelectorAll('.article--full h2, .article--full h3')
).filter(el => !el.closest('.toc-excluded'));
headings.forEach(hd => hd.classList.add("red"));
.red {
color: red;
}
h2,
h3 {
color: black;
}
<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>
返回的NodeList在过滤前必须转为数组,因为列表本身是read-only,不支持filter
方法。 header元素需要自己的CSS,否则字体颜色是继承的,不会有任何视觉差异。
我如何包含 DOM 结构中的所有 .article-full h2
和 .article-full h3
,但包含在中的 h2 和 h3 除外
.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>
:not
的所有语法还没有完全支持,因此最好还是依赖旧的好 JS。正如 Liam 所建议的,您必须过滤要从列表中排除的元素,如下所示:
const headings = Array.from(
document.querySelectorAll('.article--full h2, .article--full h3')
).filter(el => !el.closest('.toc-excluded'));
headings.forEach(hd => hd.classList.add("red"));
.red {
color: red;
}
h2,
h3 {
color: black;
}
<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>
返回的NodeList在过滤前必须转为数组,因为列表本身是read-only,不支持filter
方法。 header元素需要自己的CSS,否则字体颜色是继承的,不会有任何视觉差异。