jQuery :first-of-type 選擇器



jQuery 中的:first-of-type 選擇器用於選擇其父元素內相同型別(例如,<p>,<div> 等)的第一個元素。此選擇器可用於設定樣式或操作其父元素內特定型別元素的首次出現。

語法

以下是 jQuery :first-of-type 選擇器的語法:

$(" :first-of-type");

引數

以下是上述語法的描述:

  • :first-of-type − 選擇其父元素內相同型別中的第一個元素。

示例 1

在下面的示例中,我們使用 jQuery :first-of-type 選擇器來選擇 <div> 內的第一個 <p> 元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Change the color of the first <p> element within the <div>
            $("div p:first-of-type").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <div>
        <p>First paragraph in div.</p>
        <p>Second paragraph in div.</p>
    </div>
</body>
</html>

執行上述程式後,所選元素將以黃色背景色突出顯示。

示例 2

在此示例中,我們選擇 <ul> 內的第一個 <li> 元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Highlight the first <li> element within the <ul>
            $("ul li:first-of-type").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <ul>
        <li>First item in list</li>
        <li>Second item in list</li>
        <li>Third item in list</li>
    </ul>
</body>
</html>

執行後,所選 <li> 專案將以黃色背景色突出顯示。

示例 3

在這裡,我們選擇 <section> 內的第一個 <h1> 元素:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>First Heading in section</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Change the font size of the first <h1> element within the <section>
            $("section h1:first-of-type").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <section>
        <h1>First heading in section</h1>
        <h1>Second heading in section</h1>
    </section>
</body>
</html>

<section> 內的第一個 <h1> 元素將以黃色背景色突出顯示。

jquery_ref_selectors.htm
廣告
© . All rights reserved.