jQuery :first-child 選擇器


jQuery 中的 :first-child 選擇器用於選擇所有元素,這些元素是其父元素的第一個子元素。

語法

語法如下−

$(":first-child")

示例

現在我們來看一個實現 :first-child() 選擇器的示例 −

<!DOCTYPE html>
<html>
<head>
<style>
   .demo {
      background-color: red;
      color: white;
      font-size: 16px;
      border: 2px blue dashed;
   }
</style>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script>
   $(document).ready(function(){
      $("p:first-child").addClass("demo");
   });
</script>
</head>
<body>
<p>This is the first line!</p>
<p>This is the second line!</p>
<p>This is the third line!</p>
<hr>
<div>
<p>One</p>
<p>Two</p>
<p>Three</p>
<p>Four</p>
</div>
<hr>
<p>This is the last line.</p>
</body>
</html>

輸出

這將產生以下輸出 −

更新日期:2019-11-05

244 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.