Open In App

jQuery wrap() Method

The wrap() method is an inbuilt method in jQuery which is used to wrap the specified element around the selected element.

Syntax:



$(selector).wrap(element, function)

Parameters:

This method accepts two parameters as mentioned above and described below:



Return Value: This method returns the selected element with the specified changes made by the wrap() method.

The below examples illustrate the wrap() method in jQuery:

Example 1: This example does not accept optional parameters.




<!DOCTYPE html>
<html>
 
<head>
    <title>The wrap() Method</title>
    <script src=
    </script>
 
    <!-- jQuery code to show the working of this method -->
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("p").wrap("<div></div>");
            });
        });
    </script>
    <style>
        div {
            background-color: lightgreen;
            padding: 20px;
            width: 200px;
            font-weight: bold;
            height: 60px;
            border: 2px solid green;
        }
    </style>
</head>
 
<body>
    <!-- click on this paragraph and see the change -->
    <p>Welcome to GeeksforGeeks!</p>
    <br>
    <button>Click Here!</button>
</body>
 
</html>

Output:

Example 2:




<!DOCTYPE html>
<html>
 
<head>
    <title>The wrap Method</title>
    <script src=
    </script>
 
    <!-- jQuery code to show the working of this method -->
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("p").wrap(function () {
                    return "<div></div>"
                });
            });
        });
    </script>
    <style>
        div {
            background-color: lightgreen;
            padding: 20px;
            width: 200px;
            font-weight: bold;
            height: 60px;
            border: 2px solid green;
        }
    </style>
</head>
 
<body>
    <!-- click on this paragraph and see the change -->
    <p>Welcome to GeeksforGeeks!</p>
    <br>
    <button>Click Here!</button>
</body>
 
</html>

Output:


Article Tags :