jQuery :first 選擇器



:first 選擇器是 jQuery 選擇器,用於選擇匹配元素集中第一個元素。

當應用於一組匹配的元素時,:first 選擇器返回該集中找到的第一個元素。如果沒有任何元素匹配選擇器表示式,則返回一個空的 jQuery 物件。

注意:如果我們想要選擇匹配元素集中最後一個元素,我們需要使用:last 選擇器。

語法

以下是 jQuery 中 :first 選擇器的語法:

$("selector:first")

引數

以下是上述語法的解釋:

  • selector: 這是一個 CSS 選擇器。它指定選擇元素的條件。例如
  • "div" 選擇所有 <div> 元素。

  • ".class" 選擇所有具有類 "class" 的元素。

  • "#id" 選擇具有 id "id" 的元素。

  • first: 將選擇過濾到匹配集中第一個元素。

示例 1

在以下示例中,我們使用 :first 選擇器來選擇第一個 <p> 元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p:first").css("background-color", "yellow");
    })
});
</script>
</head>
<body>
   <p>This is the first paragraph.</p>
   <p>This is the second paragraph.</p>
   <p>This is the third paragraph.</p>
<button>Click</button>
</body>
</html>

當我們點選按鈕時,DOM 中第一個段落元素將以黃色背景顏色突出顯示。

示例 2

這裡,我們使用 :first 選擇器選擇第一個 div 元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("div:first").css("background-color", "yellow");
    })
});
</script>
</head>
<body>
   <div>This is the first div.</div>
   <div>This is the second div.</div>
   <div>This is the third div.</div>
<button>Click</button>
</body>
</html>

點選按鈕後,將選擇 DOM 中的第一個元素。

示例 3

在這個例子中,我們使用 :first 選擇器選擇第一個具有類 "highlight" 的元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $(".highlight:first").css("background-color", "yellow");
    })
});
</script>
</head>
<body>
<p class="highlight">This is the FIRST paragraph.</p>
<p>This is a normal paragraph.</p>
<p class="highlight">This is another paragraph.</p>
<button>Click</button>
</body>
</html>

執行上述程式後,它將選擇第一個具有類 "highlight" 的元素,並以黃色背景顏色突出顯示。

jquery_ref_selectors.htm
廣告