html - 匹配整个文档中某一类型的第一个/第n个元素

标签 html css css-selectors

如何指定 :first-of-type整个文件的?

我想设计第一个<p> HTML,无论它位于何处(我不想写 section p:first-of-type 因为它可能位于不同 HTML 文档的其他位置)。

p {
  background:red;	
}

p:first-of-type {
  background:pink;
}

p:last-of-type {
  background:yellow;	
}
<body>
  <section>
    <p>111</p>
    <p>222</p>
    <p>333</p>
  </section>
  <p>444</p>
  <p>555</p>
</body>

最佳答案

不幸的是,仅靠 CSS 是不可能的。 :first-of-type 伪类的文档 states :

The :first-of-type pseudo-class represents an element that is the first sibling of its type in the list of children of its parent element.

这意味着 :first-of-type 应用于其类型相对于其父元素的第一个元素,而不是文档的根(或 body 元素,在这种情况下)。


JavaScript 解决方案

:first-of-type

我们可以通过引入一些 JavaScript 来实现这一点。为此,我们只需要 JavaScript 的 querySelector() 方法,它从指定的选择器中提取第一个匹配元素。

在这个例子中,我改变了你的 :first-of-type 伪类,改为“first-of-type”类,然后使用 JavaScript 将这个类添加到使用 querySelector('p') 时返回的元素:

document.querySelector('p').className += ' first-of-type';
p {
  background:red;	
}


p.first-of-type {
  background: pink;
}
<body>
  <section>
    <p>111</p>
    <p>222</p>
    <p>333</p>
  </section>
  <p>444</p>
  <p>555</p>
</body>

:nth-child:last-of-type

至于 :nth-child:last-of-type,我们可以使用 JavaScript 提供的类似方法:querySelectorAll() 。此方法将 所有 匹配元素拉入 NodeList(类似于数组),然后我们可以遍历或通过索引从中选择特定元素:

var elems = document.querySelectorAll('p');

// nth-of-type = NodeList[n - 1]
// e.g. to select the 3rd p element ("333"):
if (elems.length >= 2)
   elems[2].className += ' nth-of-type';

// last-of-type = NodeList length - 1
if (elems.length)
   elems[elems.length - 1].className += ' last-of-type';
p {
  background:red;	
}


p.nth-of-type {
  background: pink;
}

p.last-of-type {
  background: yellow;
}
<body>
  <section>
    <p>111</p>
    <p>222</p>
    <p>333</p>
  </section>
  <p>444</p>
  <p>555</p>
</body>

请注意,我在两个选择器周围都包含了 if 语句,以确保 elems NodeList 具有足够的元素,否则将引发错误。

关于html - 匹配整个文档中某一类型的第一个/第n个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31401391/

相关文章:

jquery - 为什么我的绝对定位 ul 会改变宽度?

jquery - 在 jQuery 中定位特定的 div

html - flex 容器的非直接子子项似乎在垂直方向上未对齐。为什么?

jquery - 如何在其容器 div 中的 div 中剪辑更大宽度的固定表

jquery - ASP.NET MVC - 应用了一种样式,未应用另一种样式

css - application.css.scss 和 application.scss 的区别

css - 为 Angular8 应用动态切换全局 CSS(客户端品牌)

css - :required or [required] CSS selector

html - 将内联 css 移动到定义中

html - 在 HTML 页面输入值中使用双引号