jQuery prev() methodThe prev() method is an inbuilt method in jQuery, which returns an immediately previous sibling of the selected element. This method traverses backward along with the previous sibling of DOM elements. SyntaxThis method accepts an optional parameter that is used to specify a selector expression that narrows down the searching of the previous sibling. Let's see some of the illustrations to understand the working of the prev() method. Example1In this example, there is a div element, including three child elements that are a ul element, a heading h2, and a paragraph element. Here, we are using the prev() method to get the previous sibling of the p element. We are not using the optional parameter of the prev() method. The prev() method will return the h2 element as it is the immediate previous sibling of paragraph p. We have to click the given button to see the effect. Test it NowOutput After the execution of the above code, the output will be - After clicking the given button, the output will be - Example2In this example, we are using the optional parameter of the prev() method to narrow down the search. Here, there is a div element, including multiple children. There are many h2 heading elements with different siblings. But we are passing the p element as the optional parameter of the prev() method. So, the method will only return the p elements that are the immediate previous sibling of the h2 element. Test it NowOutput After the execution of the above code, the output will be - In the above screenshot, we can notice the siblings of the h2 element. But the method will return only the p element, as we have passed the p element as the optional parameter of the prev() method. After clicking the given button, the output will be - Example3It is another example of using the prev() method. The prev() method will trigger on clicking the given button and start traversing through the DOM elements. The method will return the immediate previous sibling of each div element and changes the background-color of corresponding div to red. Test it NowOutput On clicking the given button, the jQuery prev() method triggers and starts traversing through the DOM elements. Next TopicjQuery prevAll() method |