获取子节点的方法有:
方法 | 说明 |
children() | 选取子节点,可以带过滤参数。但只能选择子节点,不能选择孙子节点。 |
find() | 选取子节点,可以带过滤参数。可以选择子节点及孙子节点。 |
children()示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<
html
>
<
head
>
<
meta
charset
=
"UTF-8"
>
<
title
>子节点
title
>
<
script
src
=
"https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
>
script
>
<
style
>
.box{
border: 1px solid blueviolet;
padding: 1px;
margin-bottom: 12px;
}
style
>
head
>
<
body
>
<
div
>
<
ul
id
=
"ul"
>
<
li
id
=
"a"
>油条
li
>
<
li
id
=
"b"
>包子
li
>
<
li
id
=
"c"
>米饺
li
>
<
li
id
=
"d"
><
a
>鱼粉
a
>
li
>
ul
>
div
>
<
script
>
$('div').children("*").attr("class", "box");
script
>
body
>
html
>
|
find()示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<
html
>
<
head
>
<
meta
charset
=
"UTF-8"
>
<
title
>子节点
title
>
<
script
src
=
"https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
>
script
>
<
style
>
.box{
border: 1px solid blueviolet;
padding: 1px;
margin-bottom: 12px;
}
style
>
head
>
<
body
>
<
div
>
<
ul
id
=
"ul"
>
<
li
id
=
"a"
>油条
li
>
<
li
id
=
"b"
>包子
li
>
<
li
id
=
"c"
>米饺
li
>
<
li
id
=
"d"
><
a
>鱼粉
a
>
li
>
ul
>
div
>
<
script
>
$('div').find("ul").attr("class", "box");
script
>
body
>
html
>
|