如何用jQuery过滤任何元素的孩子
在这篇文章中,我们将学习如何在JQuery中过滤任何元素的孩子。JQuery是一个快速和轻量级的JavaScript库,它简化了HTML/CSS文档,或更准确地说,文档对象模型(DOM)和JavaScript之间的互动。它因其 “少写多做 “的格言而广为人知。这意味着你只需写几行代码就能完成你所需要的东西。
方法:我们可以通过选择适当的选择器来实现这一任务。例如,如果我们选择第一个孩子的选择器,那么只有第一个孩子将被突出显示,如果我们选择最后一个孩子的选择器,那么最后一个孩子将被突出显示。
儿童过滤器被分为以下几类。
- first-child 选择器。这个选择器用于选择所有是其父辈的第一个孩子的元素。
- first-of-type选择器。这个选择器用于选择所有在相同元素名称的兄弟姐妹中排在第一位的元素。
- Last-child选择器。这个选择器用于选择所有是其父辈的最后一个孩子的元素。
- last-of-type选择器。这个选择器用于选择所有在同名元素的兄弟姐妹中排在最后的元素。
- nth-child() 选择器。这个选择器用于选择所有是其父级的第n个孩子的元素。
- nth-last-child() 选择器。这个选择器用于选择所有是其父级的第n个孩子的元素,从最后一个元素算起,到第一个元素。
- nth-last-of-type() 选择器。这个选择器用于选择所有与同名元素相关的父级第n个孩子的元素,从最后一个元素算起,到第一个元素。
- nth-of-type() 选择器。这个选择器用于选择所有与同名元素相关的父辈的第n个孩子的元素。
- only-child选择器。这个选择器用于选择所有是其父辈唯一子女的元素。
- only-of-type选择器。这个选择器用于选择所有没有相同元素名称的兄弟姐妹的元素。
例子1:在这个例子中,我们将使用first-child Selector来选择其父辈的第一个子元素。
<!doctype html>
<html lang="en">
<head>
<style>
span {
color: black;
}
span.thisgreen {
color: green;
font-weight: bolder;
}
body {
text-align: center;
}
</style>
<script src=
"https://code.jquery.com/jquery-3.5.0.js">
</script>
</head>
<body>
<h1 style="color:green">GeeksForGeeks</h1>
<div>
<span>Database,</span>
<span>OS,</span>
<span>Computer Networks</span>
</div>
<div>
<span>Windows,</span>
<span>Linux,</span>
<span>MacOS</span>
</div>
<script>
("div span:first-child")
.css("text-decoration", "underline")
.hover(function () {
(this).addClass("thisgreen");
}, function () {
$(this).removeClass("thisgreen");
});
</script>
</body>
</html>
输出:
例子2:在这个例子中,我们将使用last-child选择器来选择它们的父元素的最后一个子元素。
<!doctype html>
<html lang="en">
<head>
<style>
span {
color: black;
}
span.thisgreen {
color: green;
font-weight: bolder;
}
body {
text-align: center;
}
</style>
<script src=
"https://code.jquery.com/jquery-3.5.0.js">
</script>
</head>
<body>
<h1 style="color:green">GeeksForGeeks</h1>
<div>
<span>Database,</span>
<span>OS,</span>
<span>Computer Networks</span>
</div>
<div>
<span>Windows,</span>
<span>Linux,</span>
<span>MacOS</span>
</div>
<script>
("div span:last-child")
.css("text-decoration", "underline")
.hover(function () {
(this).addClass("thisgreen");
}, function () {
$(this).removeClass("thisgreen");
});
</script>
</body>
</html>
输出: