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


The .addBack() method causes the previous set of DOM elements in the traversal stack to be added to the current set. In the first example, the top stack contains the set resulting from .find("p"). In the second example, .addBack() adds the previous set of elements on the stack — in this case $("div.after-addback") — to the current set, selecting both the div and its enclosed paragraphs.

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
45
46
47
48
49
50
51
52
53
54
55
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>addBack demo</title>
<style>
p, div {
margin: 5px;
padding: 5px;
}
.border {
border: 2px solid red;
}
.background {
background: yellow;
}
.left, .right {
width: 45%;
float: left;
}
.right {
margin-left: 3%;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div class="left">
<p><strong>Before <code>addBack()</code></strong></p>
<div class="before-addback">
<p>First Paragraph</p>
<p>Second Paragraph</p>
</div>
</div>
<div class="right">
<p><strong>After <code>addBack()</code></strong></p>
<div class="after-addback">
<p>First Paragraph</p>
<p>Second Paragraph</p>
</div>
</div>
<script>
$( "div.left, div.right" ).find( "div, div > p" ).addClass( "border" );
// First Example
$( "div.before-addback" ).find( "p" ).addClass( "background" );
// Second Example
$( "div.after-addback" ).find( "p" ).addBack().addClass( "background" );
</script>
</body>
</html>

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