html - 如何使用具有不同父级的 CSS 选择器获取第一个匹配的元素?
问题描述
使用以下 HTML:
<div>
<span class="something">...</span>
<span class="something">...</span>
<span class="something">...</span>
</div>
<article>
<span class="something">...</span>
</article>
我想找到第一个.something
。我该怎么做?
解决方案
仅使用 CSS 是无法实现的。但是,JavaScriptdocument.querySelector
可用于获取页面上与选择器匹配的第一个元素。
const first = document.querySelector('.something');
first.style.backgroundColor = "dodgerblue";
<div>
<span class="something">...</span>
<span class="something">...</span>
<span class="something">...</span>
</div>
<article>
<span class="something">...</span>
</article>
为了影响伪元素,您可以为找到的元素添加一个类,document.querySelector
并在您的 CSS 中添加另一个样式声明。
const first = document.querySelector('.something');
first.classList.add("first");
.something.first:after {
content: "I'm the first one!";
color: dodgerblue;
}
<div>
<span class="something">...</span>
<span class="something">...</span>
<span class="something">...</span>
</div>
<article>
<span class="something">...</span>
</article>