Learn all about the jQuery function .addBack().
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:
The result of the following code is a red background behind items 3, 4 and 5:
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: