How to usewrap() method in JQuery

  • We include the jQuery library in the <head> section.
  • We have a <div> with the ID elementToWrap, which contains the content you want to wrap.
  • In the jQuery script, we use the .wrap() method to wrap #elementToWrap with another <div> with the class wrapper.
  • Optional CSS is provided to style the wrapper <div> for demonstration purposes.

Example: This example shows the implementation of the above-explained approach.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width
                                   , initial-scale=1.0">
    <title>Wrap Element with Another Div</title>
    <script src=
"https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function () {
            // Wrap the element with another <div>
            $('#elementToWrap').wrap('<div class="wrapper"></div>');
        });
    </script>
    <style>
        /* Styling for wrapper and wrapped divs */
        .wrapper {
            border: 2px solid #ccc;
            padding: 10px;
            margin: 20px;
            /* Added margin for spacing */
        }
 
        #elementToWrap {
            background-color: #f0f0f0;
            padding: 10px;
        }
    </style>
</head>
 
<body>
 
    <!-- The element you want to wrap -->
    <div id="elementToWrap">
        Wrapped content
    </div>
 
</body>
 
</html>


Output:

How to Wrap an Element with Another Div Using jQuery?

We will see how to wrap an element with another div in jQuery. We will simply wrap an element inside a div tag in jQuery.

These are the following approaches:

Table of Content

  • Using wrap() method
  • Using wrap.inner() method

Similar Reads

Approach 1: Using wrap() method

We include the jQuery library in the section. We have a