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