jQuery prev() Method



The prev() method is used to select the immediately preceding sibling of the selected element(s). A sibling is an element that shares the same parent with another element. This method traverses the DOM (Document Object Model) upwards and finds the previous sibling element.

The prev() method only selects the immediately preceding sibling, not all preceding siblings. To select all preceding siblings, you can use the prevAll() method.

Syntax

Following is the syntax of prev() method in jQuery() −

$(selector).prev(filter)

Parameters

This method accepts the following optional parameter −

  • filter: A selector expression to filter the preceding sibling elements.

Example 1

In the following example, we are using the traversal() method to return the previous sibling element of p element −

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
  <script>
    $(document).ready(function(){
        $("p").prev().css({"color": "#40a944", "border": "2px solid #40a944"});
    });
  </script>
</head>
<body>
  <h2>This is heading.</h2>
  <p>Paragraph element.</p>
</body>
</html>

When we execute the above program, the h element will be selected as it is the previous sibling of p element.

Example 2

In this example below, we are selecting the previous sibling element of each div element −

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
  <script>
    $(document).ready(function(){
        $("div").prev().css({"color": "#40a944", "border": "2px solid #40a944"});
    });
  </script>
</head>
<body>
  <p>Heading element.</p>
  <div>DIV 1</div>
  <p>Paragraph element.</p>
  <p>Paragraph element.</p>
  <div>DIV 2</div>
</body>
</html>

After executing the above program, previous sibling elemens of div element will be highlighted with green border and green text color.

jquery_ref_traversing.htm
Advertisements