Learn all about the jQuery function .prev().
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:
To select the element that comes immediately before item three:
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.