jQuery Traversal - prev() Method
Example
Retrieve each paragraph and find the previous sibling element with the class name "selected":
$("p").prev(".selected")
Definition and Usage
prev() gets the previous sibling element of each element in the matching element collection, and it is optional to filter by selector.
.prev(selector)
Parameter | Description |
---|---|
selector | String value, containing the selector expression used to match elements. |
Detailed Description
If a jQuery object representing a set of DOM elements is given, the .prev() method allows us to search for the previous sibling elements of these elements in the DOM tree and construct a new jQuery object with matching elements.
This method accepts an optional selector expression, which is of the same type as the parameter we pass to the $() function. If this selector is applied, the elements will be filtered by checking if they match the selector.
Think about this page with a basic nested list:
<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>
If we start from the third item, we can find the adjacent element between them:
$('li.third-item').prev().css('background-color', 'red');
The result of the call here is to set the background color of project 2 to red. Since we did not apply a selector expression, the previous element naturally became part of the object. If a selector has been applied, the element will be checked to see if it matches the selector before it is included.