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


Find the ancestors of <li class="item-a"> up to <ul class="level-1"> and give them a red background color. Also, find ancestors of <li class="item-2"> that have a class of "yes" up to <ul class="level-1"> and give them a green border.

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>parentsUntil demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<ul class="level-1 yes">
<li class="item-i">I</li>
<li class="item-ii">II
<ul class="level-2 yes">
<li class="item-a">A</li>
<li class="item-b">B
<ul class="level-3">
<li class="item-1">1</li>
<li class="item-2">2</li>
<li class="item-3">3</li>
</ul>
</li>
<li class="item-c">C</li>
</ul>
</li>
<li class="item-iii">III</li>
</ul>
<script>
$( "li.item-a" )
.parentsUntil( ".level-1" )
.css( "background-color", "red" );
$( "li.item-2" )
.parentsUntil( $( "ul.level-1" ), ".yes" )
.css( "border", "3px solid green" );
</script>
</body>
</html>

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