jQuery :last-of-type 選擇器



jQuery 中的:last-of-type 選擇器用於選擇其父元素內同類型(標籤名稱)的最後一個元素。此選擇器目標並應用樣式或操作父元素內特定元素型別的最後一次出現。

語法

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

$("parent-selector child-selector:last-of-type")

引數

以下是上述語法的描述:

  • parent-selector: 包含子元素的父元素的選擇器。
  • child-selector: 要選擇的子元素型別的選擇器。

示例 1

在下面的示例中,我們使用 jQuery :last-of-type 選擇器來選擇其父元素(<body>)的最後一個 <p> 元素:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("p:last-of-type").css("background-color", "yellow");
});
</script>
</head>
<body>

<p>The first paragraph in body.</p>
<p>The last paragraph in body.</p>
</body>
</html>

執行上述操作後,body 中的最後一個 <p> 元素將以黃色背景色突出顯示。

示例 2

在這個示例中,我們選擇所有 <div> 元素中的最後一個 <p> 元素:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("div p:last-of-type").css("background-color", "yellow");
});
</script>
</head>
<body>

<div style="border:1px solid;">
  <p>The first paragraph in div.</p>
  <p>The last paragraph in div.</p>
</div><br>

<div style="border:1px solid;">
  <p>The first paragraph in another div.</p>
  <p>The last paragraph in another div.</p>
  <span>This is a span element.</span>
</div>

</body>
</html>

執行後,<div> 內選擇的 <p> 元素將以黃色背景色突出顯示。

示例 3

在這裡,我們選擇 DOM 內所有最後一個 <p> 元素:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("p:last-of-type").css("background-color", "yellow");
});
</script>
</head>
<body>

<p>The first paragraph in body.</p>
<div style="border:1px solid;">
  <p>The first paragraph in div.</p>
  <p>The last paragraph in div.</p>
</div><br>
<div style="border:1px solid;">
  <p>The first paragraph in another div.</p>
  <p>The last paragraph in another div.</p>
  <span>This is a span element.</span>
</div>
<p>The last paragraph in body.</p>
</body>

</html>

<div> 元素內的最後一個段落元素和 DOM 中的最後一個元素將以黃色背景色突出顯示。

jquery_ref_selectors.htm
廣告