jquery
  1. jquery-prev

JQuery prev()

Syntax

The prev() method in jQuery selects the immediately preceding sibling element of the currently selected element.

$(selector).prev();

Use

The prev() method is most commonly used to target the previous sibling element of a specific HTML element. It can be used to retrieve and manipulate the content of a particular element in your web page's DOM.

Example

Here is an example of using prev() to target and manipulate the content of the previous sibling element of a specific HTML element:

<!doctype html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $(this).prev().html("Previous paragraph has been changed.");
            });
        });
    </script>
</head>
<body>

    <p>This is the first paragraph.</p>
    <p>This is the second paragraph.</p>

    <button>Change Text</button>

</body>
</html>
Try Playground

In this example, when the button is clicked, it targets the previous sibling element of the button, which is the second paragraph. Then it changes the text of the second paragraph to "Previous paragraph has been changed."

Summary

The prev() method is a useful way to select the immediately preceding sibling element of the currently selected element. It can be used to retrieve and manipulate the content of a particular element in your web page's DOM and is often used in combination with other jQuery methods to select and manipulate a specific element. Give it a try in your next jQuery project.

Published on: