Given a jQuery object that represents a set of DOM elements, the .prev()
method searches for the predecessor of each of these elements in the DOM tree and constructs a new jQuery object from the matching elements.
The method optionally accepts a selector expression of the same type that can be passed to the $()
function. If the selector is supplied, the preceding element will be filtered by testing whether it match the selector.
Consider a page with a simple list on it:
<ul> <li>list item 1</li> <li>list item 2</li> <li class="third-item">list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul>
To select the element that comes immediately before item three:
$( "li.third-item" ).prev().css( "background-color", "red" );
The result of this call is a red background behind item 2. Since no selector expression is supplied, this preceding element is unequivocally included as part of the object. If one had been supplied, the element would be tested for a match before it was included.
If no previous sibling exists, or if the previous sibling element does not match a supplied selector, an empty jQuery object is returned.
To select all preceding sibling elements, rather than just the preceding adjacent sibling, use the .prevAll() method.
A string containing a selector expression to match elements against.
Find the very previous sibling of each div.
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>prev demo</title> <style> div { width: 40px; height: 40px; margin: 10px; float: left; border: 2px blue solid; padding: 2px; } span { font-size: 14px; } p { clear: left; margin: 10px; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <div></div> <div></div> <div><span>has child</span></div> <div></div> <div></div> <div></div> <div id="start"></div> <div></div> <p><button>Go to Prev</button></p> <script> var $curr = $( "#start" ); $curr.css( "background", "#f99" ); $( "button" ).click(function() { $curr = $curr.prev(); $( "div" ).css( "background", "" ); $curr.css( "background", "#f99" ); }); </script> </body> </html>
For each paragraph, find the very previous sibling that has a class "selected".
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>prev demo</title> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <div><span>Hello</span></div> <p class="selected">Hello Again</p> <p>And Again</p> <script> $( "p" ).prev( ".selected" ).css( "background", "yellow" ); </script> </body> </html>
Please login to continue.