jQuery 提供了许多可以用来获取父母、子女、兄弟姐妹、先前和下一个元素的树交叉功能,我们将逐一探讨每一种 jQuery 树交叉方法,今天我们将探讨两种 jQuery 树交叉方法,即父母( )
和孩子( )
。
jQuery 家长() 函数
**jQuery parent() 方法用于获取所选 HTML 元素的直接父母元素. 一旦返回,您可以对父母元素执行所需的操作。
- $(「子」=「子」=「子」=「子」=「子」。
这将返回 parent 元素的直接家长
$(_孩子
_)。父母(过滤器
)*
** 过滤器是传递给 parent() 方法的可选参数。
jQuery parent() 函数示例
下面的示例显示了 parent() 方法的使用。 jquery-parent.html
1<!DOCTYPE html>
2<html>
3<head>
4<title>jQuery Traversing Parent</title>
5
6<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
7<script>
8$(document).ready(function(){
9 $("h4").parent().css("background-color","yellow");
10});
11</script>
12</head>
13<body>
14
15<span id="spanParent">Span Element - Parent of h4 element
16<h4>This is an h4 element - child of Span.</h4>
17</span>
18
19</body>
20</html>
In this example, the parent element is and is the child element. The parent() method is used to get the direct parent element which is the element and changes the background color. The parent() method traverses only one level up the HTM DOM tree. The optional parameters provide additional filtering options to narrow down the traversal. Below image shows the output produced by above HTML page, notice the background color of span element is yellow.
jQuery 儿童() 功能
**jQuery 子女() 方法用于获取所选 HTML 元素的直接子女. 您可以使用子女() 方法穿过所选父母元素的子女元素。 您可以对子女元素执行所需的操作,如更改背景颜色、启用、禁用、隐藏、显示等,使用此方法。
- $(
_parentElement
_)。儿童()
它被用来返回 **parentElement**的所有直接子女。
- $(「子女元素」) 子女元素(「子女元素」)
_parentElement和 _childElement可以是任何HTML元素.这将返回 **_parentElement的所有匹配的 childElement。
jQuery 儿童() 函数示例
以下示例显示了儿童() 方法的使用。 jquery-children.html
1<html>
2<head>
3<title>jQuery Traversing Children</title>
4
5<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
6<script>
7$(document).ready(function(){
8 //below code will run for all divs
9 $("div").children("p").css("background-color","yellow");
10
11 $("#spanParent").children("h4").css("background-color","green");
12});
13</script>
14</head>
15<body>
16
17<div style="border:1px solid;">
18<h3>h3 - Child of div</h3>
19<p> p -Child of div</p>
20<span> Span - Child of Div</span>
21<p>Second p - Child of div</p>
22</div>
23<p> p element - Not a child of div</p>
24
25<span id="spanParent">
26<h4>This is an h4 element (child of Span).</h4>
27</span>
28
29</body>
30</html>
In this example, you can see two parent elements:
of the parent
elements to yellow. Notice the p element outside the div element is not altered by this method. Likewise, span element has child element h4 and we change the color of that element in this example. The children method traverses only one level down the HTM DOM tree. This method is not used to traverse through the text nodes. Below is the output produced by the above HTML page. That's all for jQuery parent and children function examples, we will look into more jQuery traversal methods in coming posts.