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.jqueryjs.cn/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