.addBack( [selector ] ) Returns: jQuery
Description: Add the previous set of elements on the stack to the current set, optionally filtered by a selector.
-
version added: 1.8.addBack( [selector ] )
-
selectorType: SelectorA string containing a selector expression to match the current set of elements against.
-
As described in the discussion for .end()
, jQuery objects maintain an internal stack that keeps track of changes to the matched set of elements. When one of the DOM traversal methods is called, the new set of elements is pushed onto the stack. If the previous set of elements is desired as well, .addBack()
can help.
Consider a page with a simple list on it:
1
2
3
4
5
6
7
|
|
The result of the following code is a red background behind items 3, 4 and 5:
1
2
|
|
First, the initial selector locates item 3, initializing the stack with the set containing just this item. The call to .nextAll()
then pushes the set of items 4 and 5 onto the stack. Finally, the .addBack()
invocation merges these two sets together, creating a jQuery object that points to all three items in document order: {[<li.third-item>,<li>,<li> ]}
.
Example:
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
|
|