Примеры для jQuery .parent()


Shows the parent of each element as (parent > child). Check the View Source to see the raw html.

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>parent demo</title>
<style>
div, p {
margin: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>div,
<span>span, </span>
<b>b </b>
</div>
<p>p,
<span>span,
<em>em </em>
</span>
</p>
<div>div,
<strong>strong,
<span>span, </span>
<em>em,
<b>b, </b>
</em>
</strong>
<b>b </b>
</div>
<script>
$( "*", document.body ).each(function() {
var parentTag = $( this ).parent().get( 0 ).tagName;
$( this ).prepend( document.createTextNode( parentTag + " > " ) );
});
</script>
</body>
</html>

Демонстрация:

Find the parent element of each paragraph with a class "selected".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>parent demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div><p>Hello</p></div>
<div class="selected"><p>Hello Again</p></div>
<script>
$( "p" ).parent( ".selected" ).css( "background", "yellow" );
</script>
</body>
</html>

Демонстрация: