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 matching element collection, 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 of the same type as the parameter passed to the $() function. If this selector is applied, it will filter elements by checking whether 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 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 became part of the object. If a selector has been applied, it will check whether these elements match the selector before including them.