📜  jQuery | :first-of-type 选择器(1)

📅  最后修改于: 2023-12-03 15:32:11.871000             🧑  作者: Mango

jQuery | :first-of-type选择器

在jQuery中,:first-of-type选择器用于选择匹配元素的父元素的第一个指定类型的子元素。

语法
$(“selector:first-of-type”)
参数

:first-of-type选择器没有参数。

示例

假设我们有一个HTML页面,如下所示:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>:first-of-type Selector Example</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <style>
      span:first-of-type {
        color: red;
      }
    </style>
  </head>
  <body>
    <div>
      <span>Hello</span>
      <span>World</span>
      <p>This is a paragraph</p>
    </div>

    <div>
      <p>This is another paragraph</p>
      <span>Goodbye</span>
      <span>Cruel World</span>
    </div>

    <script>
      $(document).ready(function(){
        $('div span:first-of-type').css('font-weight', 'bold');
      });
    </script>
  </body>
</html>

代码中,我们定义了一个:first-of-type选择器,它被应用到span元素上。通过使用JavaScript和jQuery,选择器会给每个匹配的元素设置一个粗体字体。

在示例中,选择器会匹配两个div标签,每个标签中包含两个span和一个p元素。选择器会选取每个div的第一个span元素并将其文本变为粗体字。

结论

:first-of-type选择器可以帮助您选择匹配元素的父元素的第一个指定类型的子元素。当您需要更改父元素的第一个子元素的样式或属性时,这个选择器非常有用。