css 第 n 个类型元素的选择器 - nth-of-type() 的奇怪实现

css selector for nth element of type - weird implementation of nth-of-type()

我可能很愚蠢,但我正在尝试 select 具有 class 特殊 class 的第二个 div。什么是正确的查询选择器?

出于测试目的,我想使用 document.querySelector("#content-wrapper > .specialclass:nth-of-type(2)"); 我认为 nth-of-type 用于此目的。但它 returns undefined.nth-of-type 以及 nth-child 似乎是从父元素算起的。问题是元素的顺序经常改变。

网站结构

 <div id="content-wrapper">
  <div class="a"></div>
  <div class="a"></div>
  <div class="specialclass">Can be selectet through document.querySelector(".specialclass:nth-of-type(3)");</div>
  <div class="a"></div>
  <div class="a"></div>
  <div class="a"></div>
  <div class="specialclass">element I'd like to select. Can be selectet through document.querySelector(".specialclass:nth-of-type(7)");</div>
  <div class="a"></div>
  <div class="a"></div>
  <div class="a"></div>
</div>

重要提示:请注意我不能更改网站标记!

:nth-of-type()中的"type"指的是元素类型,在本例中是div。由于子级都是 div 元素,因此 :nth-of-type() 的功能与 :nth-child() 相同。这完全是设计使然。

虽然 trying to select the nth child matching a specific selector 的一般问题通常与对 :nth-of-type() 工作原理的误解有关,但这个问题与其他问题并不完全相同,因为它们都是 CSS-based,这带来了 select 或 API 中不存在的某些限制,例如 DOM.

提供的限制

在您的特定情况下,您可以使用 querySelectorAll() 来 select 所有 .specialclass 元素并关闭索引,而不是尝试使用 querySelector() 检索单个元素得到你想要的节点列表(记住这是一个从零开始的索引,不像结构伪 类 是从一开始的):

var secondElement = document.querySelectorAll("#content-wrapper > .specialclass")[1];

也可以使用类似

的东西
var secondElement = document.querySelector("#content-wrapper > .specialclass ~ .specialclass");

如评论中所述,querySelector()(注意:不是 querySelectorAll())只会选择第一个这样的元素——这始终是最接近的 .specialclass第一个 .specialclass 的同级,不管这些元素有多少。但是我更喜欢索引节点列表,因为意图更清晰。