
- jQuery - Home
- jQuery - Roadmap
- jQuery - Overview
- jQuery - Basics
- jQuery - Syntax
- jQuery - Selectors
- jQuery - Events
- jQuery - Attributes
- jQuery - AJAX
- jQuery CSS Manipulation
- jQuery - CSS Classes
- jQuery - Dimensions
- jQuery - CSS Properties
- jQuery Traversing
- jQuery - Traversing
- jQuery - Traversing Ancestors
- jQuery - Traversing Descendants
- jQuery References
- jQuery - Selectors
- jQuery - Events
- jQuery - Effects
- jQuery - HTML/CSS
- jQuery - Traversing
- jQuery - Miscellaneous
- jQuery - Properties
- jQuery - Utilities
- jQuery Plugins
- jQuery - Plugins
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
jQuery prev() Method
The prev() method is used to select the immediately preceding sibling of the selected element(s). A sibling is an element that shares the same parent with another element. This method traverses the DOM (Document Object Model) upwards and finds the previous sibling element.
The prev() method only selects the immediately preceding sibling, not all preceding siblings. To select all preceding siblings, you can use the prevAll() method.
Syntax
Following is the syntax of prev() method in jQuery() −
$(selector).prev(filter)
Parameters
This method accepts the following optional parameter −
- filter: A selector expression to filter the preceding sibling elements.
Example 1
In the following example, we are using the traversal() method to return the previous sibling element of p element −
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("p").prev().css({"color": "#40a944", "border": "2px solid #40a944"}); }); </script> </head> <body> <h2>This is heading.</h2> <p>Paragraph element.</p> </body> </html>
When we execute the above program, the h element will be selected as it is the previous sibling of p element.
Example 2
In this example below, we are selecting the previous sibling element of each div element −
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("div").prev().css({"color": "#40a944", "border": "2px solid #40a944"}); }); </script> </head> <body> <p>Heading element.</p> <div>DIV 1</div> <p>Paragraph element.</p> <p>Paragraph element.</p> <div>DIV 2</div> </body> </html>
After executing the above program, previous sibling elemens of div element will be highlighted with green border and green text color.