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

use*_*092 8 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;	
}
Run Code Online (Sandbox Code Playgroud)
<body>
  <section>
    <p>111</p>
    <p>222</p>
    <p>333</p>
  </section>
  <p>444</p>
  <p>555</p>
</body>
Run Code Online (Sandbox Code Playgroud)

Jam*_*lly 8

仅使用CSS,这是不可能的.:first-of-type伪类的文档说明:

:first-of-type伪类表示是其在它的父元素的孩子的列表类型的第一个同级的元素.

这意味着它: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';
Run Code Online (Sandbox Code Playgroud)
p {
  background:red;	
}


p.first-of-type {
  background: pink;
}
Run Code Online (Sandbox Code Playgroud)
<body>
  <section>
    <p>111</p>
    <p>222</p>
    <p>333</p>
  </section>
  <p>444</p>
  <p>555</p>
</body>
Run Code Online (Sandbox Code Playgroud)

: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';
Run Code Online (Sandbox Code Playgroud)
p {
  background:red;	
}


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

p.last-of-type {
  background: yellow;
}
Run Code Online (Sandbox Code Playgroud)
<body>
  <section>
    <p>111</p>
    <p>222</p>
    <p>333</p>
  </section>
  <p>444</p>
  <p>555</p>
</body>
Run Code Online (Sandbox Code Playgroud)

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