EN
jQuery - how to use parents function example
12 points
Using jQuery it is possible to traverse elements with parents
method in the following ways.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
div { padding: 5px; }
7
8
#my-parent-3 { border: 3px solid red; }
9
#my-parent-2 { border: 3px solid green; }
10
#my-parent-1 { border: 3px solid orange; }
11
12
#my-element {
13
border: 3px solid blue;
14
}
15
16
</style>
17
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
18
</head>
19
<body>
20
<div id="my-parent-3">
21
<div id="my-parent-2">
22
<div id="my-parent-1">
23
<div id="my-element">My element...</div>
24
</div>
25
</div>
26
</div>
27
<script>
28
29
$(document).ready(function() {
30
var element = $('#my-element');
31
var parents = element.parents();
32
33
parents.css('border-width', '10px');
34
});
35
36
</script>
37
</body>
38
</html>
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
div { padding: 5px; }
7
8
#my-parent-3 { border: 3px solid red; }
9
#my-parent-2 { border: 3px solid green; }
10
#my-parent-1 { border: 3px solid orange; }
11
12
#my-element { border: 3px solid blue; }
13
14
</style>
15
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
16
</head>
17
<body>
18
<div id="my-parent-3" class="bound">
19
<div id="my-parent-2" class="middle">
20
<div id="my-parent-1" class="bound">
21
<div id="my-element">My element...</div>
22
</div>
23
</div>
24
</div>
25
<script>
26
27
$(document).ready(function() {
28
var element = $('#my-element');
29
30
// 'div.bound' can be replaced with any css selector
31
var parents = element.parents('div.bound');
32
33
parents.css('border-width', '10px');
34
});
35
36
</script>
37
</body>
38
</html>