jQuery wrap()

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

jQuery wrap()

jQuery wrap() method is used to wrap specified HTML elements around each selected element. The wrap () function can accept any string or object that could be passed through the $() factory function.

Syntax:

  1. $(selector).wrap(wrappingElement,function(index))   

Parameters of jQuery wrap() method

Parameter Description
WrappingElement It is a mandatory parameter. It specifies what HTML elements to wrap around each selected element. Its possible values are:
  • HTML elements
  • jQuery objects
  • DOM elements
Function(index) It is an optional parameter. It specifies a function that returns the wrapping element.
  • Index: It provides the index position of the element in the set.

Example of jQuery wrap() method

Let's take an example to demonstrate the jQuery wrap() method.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
  5. <script>  
  6. $(document).ready(function(){  
  7.     $("button").click(function(){  
  8.         $("p").wrap("<div></div>");  
  9.     });  
  10. });  
  11. </script>  
  12. <style>  
  13. div{background-color: pink;}  
  14. </style>  
  15. </head>  
  16. <body>  
  17. <p>Hello Guys!</p>  
  18. <p>This is javatpoint.com</p>  
  19. <button>Wrap a div element around each p element</button>  
  20. </body>  
  21. </html>  

Test it Now

jQuery wrap() example 2

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <title>The jQuery Example</title>  
  5. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>  
  6. <script type="text/javascript" language="javascript">  
  7.          $(document).ready(function() {  
  8.             $("div").click(function () {  
  9.                var content = '<div class="div"></div>';  
  10.                $("#destination").wrap( content );  
  11.             });  
  12.          });  
  13. </script>  
  14. <style>  
  15. .div{ margin:5px;padding:2px; border:2px solid #666; width:60px;}</style>  
  16. </head>  
  17. <body>  
  18. <p>Click on any square to wrap the text:</p>  
  19. <div class="div" id="destination">We are going to wrap this text</div>  
  20. <div class="div" style="background-color:orange;">ONE</div>  
  21. <div class="div" style="background-color:yellow;">TWO</div>  
  22. <div class="div" style="background-color:green;">THREE</div>  
  23. </body>  
  24. </html>  

Test it Now