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>輸出
這將產生以下輸出 −

廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP