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:
$(selector).wrap(wrappingElement,function(index))
Parameter | Description |
---|---|
WrappingElement | It is a mandatory parameter. It specifies what HTML elements to wrap around each selected element. Its possible values are:
|
Function(index) | It is an optional parameter. It specifies a function that returns the wrapping element.
|
Let's take an example to demonstrate the jQuery wrap() method.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").wrap("<div></div>"); }); }); </script> <style> div{background-color: pink;} </style> </head> <body> <p>Hello Guys!</p> <p>This is rookienerd.com</p> <button>Wrap a div element around each p element</button> </body> </html>
<!DOCTYPE html> <html> <head> <title>The jQuery Example</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script type="text/javascript" language="javascript"> $(document).ready(function() { $("div").click(function () { var content = '<div class="div"></div>'; $("#destination").wrap( content ); }); }); </script> <style> .div{ margin:5px;padding:2px; border:2px solid #666; width:60px;}</style> </head> <body> <p>Click on any square to wrap the text:</p> <div class="div" id="destination">We are going to wrap this text</div> <div class="div" style="background-color:orange;">ONE</div> <div class="div" style="background-color:yellow;">TWO</div> <div class="div" style="background-color:green;">THREE</div> </body> </html>