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 it is optional to filter through a selector.

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

Detailed Explanation

If a jQuery object representing a collection 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, it will filter the elements by checking whether the elements 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 of the call here is to set the background color of item 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 whether the element matches the selector before including the element.

" -->