jQuery Traversal - prevAll() Method

Example

Locate all divs before the last div and add the class to them:

$("div:last").prevAll().addClass("before");

Try it yourself

Definition and Usage

prevAll() gets the preceding sibling elements of each element in the current matched element set, and using a selector for filtering is optional.

Syntax

.prevAll(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 .prevAll() method allows us to search for the preceding 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 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 sibling elements between the elements:

$('li.third-item').prevAll().css('background-color', 'red');

Try it yourself

The result of the call here is to set the background color of item 2 and item 1 to red. Since we did not apply a selector expression, these preceding elements naturally become part of the object. If a selector has been applied, it will check whether these elements match the selector before including the elements.