jQuery Traversal - prev() Method

Example

Retrieve each paragraph and find the previous sibling element with the class name "selected":

$("p").prev(".selected")

Try it yourself

Definition and Usage

prev() gets the previous sibling element of each element in the matching element collection, and filtering by selector is optional.

.prev(selector)
Parameter Description
selector String value, containing the selector expression used to match elements.

Detailed Explanation

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 the same type of parameter as the one we pass to the $() function. If this selector is applied, it will filter the elements 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');

Try it yourself

The result called 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, it will check if the element matches the selector before including the element.

" -->