Jquery children()方法
jQuery中的
children()方法返回给定选择器的直接子级。它是
JQuery 中的内置方法。此方法仅遍历DOM树下的单个级别。我们可以使用
find()方法向下遍历多个级别。
假设我们有一个jQuery对象表示元素集,因此
children()方法在DOM树中向下搜索,并构造一个包含匹配元素子集的新jQuery对象。
children()方法不返回文本节点。我们可以使用
contents()方法获取所有带有文本节点的子级。
使用
children()方法的语法如下:
语法
$(selector).children(filter)
此方法接受可选参数,即
filter 。
filter: 是可选值用于缩小搜索范围。它是一个选择器表达式,其类型可以与传递给
$()函数的类型相同。
现在,我们将看到一些使用
children()方法。在第一个示例中,我们不使用可选参数值,而在第二个示例中,我们在使用可选值来缩小搜索范围。
Example1
在此示例中,有一个div元素以及两个
ul元素,标题
h2 和段落元素。在这里,我们使用
children()方法来获取
div的直接子级元素。这两个
ul 元素都是
div 元素的直接子元素,因此,
children()方法将同时返回这两个
ul 元素作为
div 元素的直接子元素。
我们必须单击给定的按钮才能看到效果。
<!DOCTYPE html>
<html>
<head>
<style>
.main * {
display: block;
font-size: 20px;
position: relative;
border: 2px solid black;
color: black;
padding: 10px;
margin: 17px;
}
</style>
<script src="/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function fun(){
$(document).ready(function(){
$("div").children().css({ "font-size": "30px", "color": "blue", "border": "6px dashed blue"});
});
}
</script>
</head>
<body class = "main"> body
<div id = "div1"> div element
<ul> First ul element
<h2> Heading h2 </h2>
</ul>
<ul> Second ul element
<p> Paragraph element </p>
</ul>
</div>
<button onclick = "fun()"> click me </button>
</body>
</html>
输出
之后单击给定的按钮,输出将是-
现在,在在下一个示例中,我们将使用
children()方法的可选参数。
Example2
在此示例中,我们是使用
过滤器值来缩小搜索范围。这里,有两个
ul 元素,它们都是
div 元素的直接子代。我们将传递第一个
ul 元素,其类名称为
first 作为
children()方法的可选参数
因此,该方法将返回相应的
ul 元素,该元素现在是给定选择器的所有子元素之间的前一个子元素。
<!DOCTYPE html>
<html>
<head>
<style>
.main * {
display: block;
font-size: 20px;
position: relative;
border: 2px solid black;
color: black;
padding: 10px;
margin: 17px;
}
</style>
<script src="/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function fun(){
$(document).ready(function(){
$("div").children("ul.first").css({ "font-size": "30px", "color": "blue", "border": "6px dashed blue"});
});
}
</script>
</head>
<body class = "main"> body
<div id = "div1"> div element
<ul class = "first"> First ul element
<h2> Heading h2 </h2>
</ul>
<ul> Second ul element
<p> Paragraph element </p>
</ul>
</div>
<button onclick = "fun()"> click me </button>
</body>
</html>
输出
执行上述代码后,输出为-
单击按钮后,我们可以看到该函数将返回具有类名称
first 。在这里,该函数将不返回第二个ul元素,它也是
div 元素的直接子代。
单击按钮后,输出为-
