jQuery prevAll() method

The prevAll() method is jQuery's inbuilt function that returns all previous siblings of the selected element. This method traverses backward along with the previous siblings of DOM elements.

Syntax

This method accepts an optional parameter that specifies a selector expression that narrows down the searching of previous siblings. If we have to return multiple siblings, we can separate every expression with a comma.

Let's see some of the illustrations to understand the working of the prevAll() method.

Example1

It is a simple example of using the prevAll() method. Here, there is a div element, including four child elements that are a ul element, a heading h2, and two paragraph elements. We are using the prevAll() method to get the previous siblings of the p element. We are not using the optional parameter of the prevAll() method.

We have to click the given button to see the effect.

Test it Now

Output

jQuery prevAll() method

After clicking the given button, all previous siblings of the p element will get selected, as shown in the below screenshot -

jQuery prevAll() method

Example2

In this example, we are using the optional parameter of the prevAll() method to narrow down the search. Here, there is a div element including multiple children. We are passing the p element as the optional parameter of the prevAll() method. So, the method will only return the p elements that are the previous siblings of the h2 element.

Test it Now

Output

jQuery prevAll() method

After clicking the given button, all previous paragraph siblings of the h2 element will get selected, as shown in the below screenshot -

jQuery prevAll() method

Example3

In this example, we are using the prevAll() method to select the p siblings of the h2 element. In the output, we can see a paragraph element which is not selected. This is because the corresponding paragraph has the different parent element among others. It does not share the same parent.

Test it Now

Output

jQuery prevAll() method

After clicking the given button, all previous paragraph siblings of the h2 element will get selected, except one paragraph that has a different parent element, as shown in the below screenshot -

jQuery prevAll() method




Latest Courses