:first-of-type選擇器用於選擇所有作為其父級的第一個子級(特定類型)的元素。
用法:
$(":first-of-type")
以下示例說明了jQuery中的first-of-type選擇器:
範例1:本示例將其父母的第一個標題(div標簽)的背景顏色更改為綠色,並將text-color更改為白色。
<!DOCTYPE html>
<html>
<head>
<title>
jQuery |:first-of-type Selector
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- Script to use first-of-child selector -->
<script>
$(document).ready(function() {
$("h4:first-of-type").css({
"background-color":"green",
"color":"white"
});
});
</script>
<style>
option {
font-weight:bold;
font-size:25px;
color:green;
}
select {
font-weight:bold;
font-size:25px;
color:green;
}
</style>
</head>
<body style="text-align:center; width:500px; margin:auto">
<h1>
jQuery |:first-of-type Selector
</h1>
<div style="border:1px solid blue;">
<h4>The first heading in first div.</h4>
<h4>The last heading in first div.</h4>
</div><br>
<div style="border:1px solid blue;">
<h4>The first heading in second div.</h4>
<h4>The last heading in second div.</h4>
</div>
</body>
</html>
輸出:
範例2:此示例將<body>標簽的第一個標題的背景顏色更改為綠色,並將text-color更改為白色。
<!DOCTYPE html>
<html>
<head>
<title>
jQuery |:first-of-type Selector
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- Script to use first-of-child selector -->
<script>
$(document).ready(function() {
$("h4:first-of-type").css({
"background-color":"green",
"color":"white"
});
});
</script>
<style>
option {
font-weight:bold;
font-size:25px;
color:green;
}
select {
font-weight:bold;
font-size:25px;
color:green;
}
</style>
</head>
<body style = "text-align:center; width:500px; margin:auto">
<h1>
jQuery |:first-of-type Selector
</h1>
<h4>The first heading in body.</h4>
<h4>The last heading in body.</h4>
</body>
</html>
輸出:
相關用法
- jQuery :even用法及代碼示例
- jQuery :first用法及代碼示例
- jQuery :odd用法及代碼示例
- jQuery :gt()用法及代碼示例
- jQuery :not()用法及代碼示例
- jQuery :last用法及代碼示例
- jQuery :lt()用法及代碼示例
- jQuery :contains()用法及代碼示例
- jQuery :header用法及代碼示例
- jQuery :parent用法及代碼示例
注:本文由純淨天空篩選整理自PranchalKatiyar大神的英文原創作品 jQuery | :first-of-type Selector。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。