jQuery :first-of-type 選擇器
jQuery 中的 :first-of-type 選擇器用於選擇元素,這些元素是其父元素的第一個元素。
語法
語法如下 −
$(":first-of-type")示例
我們現在來看一個示例來實現 :first-of-type() 選擇器 −
<!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-of-type").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>
<span>One</span>
<p>Two</p>
<span>Three</span>
<p>Four</p>
</div>
<hr>
<div>
<p>A</p>
<p>B</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