The jQuery addBack() method can be used to add the previous set of elements to the current. The method adds the previous set of elements to the current set of elements and pushed onto the stack. The jQuery DOM object then maintains an internal stack that keeps track of changes to the matched set of elements.
Syntax
The syntax of this method is given below:-
Description of the Parameters
The description of these parameters is given below.
Parameter Name | Description |
---|---|
selector | Specify the element to select and add back the specified element. You can use the element tag name, class name, or id to select. It is a required field. |
selectElement | It can be an HTML element, jQuery object, or selector expression to match the current set of elements against. It is an optional field. |
jQuery addBack() Method to Add Previous Set of Element to Current
If you want to add the previous set of elements to the current set, you have to use the method as given below. The example contains paragraph elements and selects all the elements after the specified item.
Example
1 2 3 4 5 6 7 8 9 10 11 12 |
<script> $(document).ready(function(){ $('.mybtn').click(function(){ $("p").nextAll().addBack().css("color","orange"); }); }); </script> <p>1st paragraph element.</p> <p>2st paragraph element.</p> <p class="mypara3">3rd paragraph element.</p> <p>4th paragraph element.</p><br><br> <button type="button" class="mybtn">Click to Add Back</button> |
Output
1st paragraph element.
2st paragraph element.
3rd paragraph element.
4th paragraph element.
When you click the button given above, it select items located from position 3rd to 5th. After that, it applies the orange color to the text of these paragraphs. The above example also uses the jQuery nextAll() method to use the above method.
You may also like to read
I hope you like this tutorial on jQuery addBack() method. If you have any queries regarding the tutorial, please comment below.
References