jQuery :only-child选择器
这是一个jQuery选择器,用于选择每一个元素,它是它的父辈的唯一的孩子,即只有一个孩子被选中。
语法:
$(":only-child")
JavaScript
示例 1:
<!DOCTYPE html>
<html>
<h1>
<center>Geeks</center>
</h1>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
(document).ready(function () {
("p:only-child").css(
"background-color", "green");
});
</script>
</head>
<body>
<div style="border:1px solid;">
<p>Geeks for Geeks</p>
</div>
<br>
<div style="border:1px solid;">
<p>Geeks for Geeks</p>
<p>jQuery:Only Child Selector</p>
</div>
<br>
</body>
</html>
HTML
输出:
示例 2:
<!DOCTYPE html>
<html>
<h1>
<center>Geeks</center>
</h1>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
(document).ready(function () {
("p:only-child").css(
"background-color", "green");
});
</script>
</head>
<body>
<div style="border:1px solid;">
<p>Geeks for Geeks</p>
</div>
<br>
<div style="border:1px solid;">
<p>Geeks for Geeks</p>
</div>
<br>
<div style="border:1px solid;">
<p>Geeks for Geeks</p>
</div>
<br>
</body>
</html>
HTML
输出: