The jQuery prevAll() method can be used to get or return all the previous siblings of the selected element. It selects the elements that share the same parent element.
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 get all the previous sibling elements. You can use the element tag name, class name, or id to select. It is a required field. |
selectorElement | Specify the elements to filter the return of all previous sibling elements. It is an optional field. |
jQuery prevAll() Method to Get All Sibling Element
If you want to find all the previous sibling elements of the selected element, you have to use the method as given below. The below example contains list elements with five list items. In these elements, you have to get all previous siblings for the starting point element.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<script> $(document).ready(function(){ $('.mybtn').click(function(){ $("ul li.4thitem").prevAll().css("color","orange"); }); }); </script> <ul> <li>1st list element</li> <li>2nd list element</li> <li>3rd list element</li> <li class="4thitem">Selected 4th list element</li> <li>5th list element</li> </ul> <button type="button" class="mybtn">Click to Get All Previous Sibling</button> |
Output
- 1st list element
- 2nd list element
- 3rd list element
- Selected 4th list element
- 5th list element
When you click the button given above, it returns all the previous siblings of the selected element. The selection traverse through the specified list element.
Return Matching Sibling Elements
You can also return the specified previous sibling matching elements from the selected element. The jQuery prevAll() method can be used as given in the example below. Pass the element tag name or class name as the parameter of the method to select all matching previous siblings.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script> $(document).ready(function(){ $('.mymtbtn').click(function(){ $("ul li.4thitem").prevAll(".myselect").css("color","green"); }); </script> <ul> <li class="myselect">First item</li> <li>Second item</li> <li class="myselect">Third item</li> <li class="4thitem">Selected Forth item</li> <li>Fifth item</li> </ul> <button type="button" class="mymtbtn">Click to Return Previous Sibling</button> |
Output
- First item
- Second item
- Third item
- Selected Forth item
- Fifth item
Click the above button to find all the matching previous sibling elements. There are two matching elements in the above list element as the all matching previous sibling elements.
You may also like to read
I hope you like this tutorial on jQuery prevAll() method. If you have any queries regarding the tutorial, please comment below.
References