The jQuery wrap() method can be used to wrap the selected element with the specified HTML element. You have to specify the HTML element to wrap around the selected element.
Syntax
The syntax of this method is given below:-
The above syntax, the function is the optional field to specify for wrapping the selected element.
Description of the Parameters
The description of the parameters is given below.
Parameter Name | Description |
---|---|
selector | Specify the element you want to select to wrap. Use tag name, class name, or id of the elements to select. It is a required field. |
htmlElement | Specify the HTML element you want to wrap the selected element. It is a required field. |
jQuery wrap() Method to Wrap Selected Element
If you want to wrap the selected element, you have to specify the HTML element as given below. The example contains the paragraph that wrapped within the div element.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<script> $(document).ready(function(){ $('.wrapbtn').click(function(){ $("p").wrap("<div></div>"); }); }); </script> <style> div{ background:#ccc; border:1px solid #000; padding:10px; } </style> <p>This is my paragraph.</p><br><br> <button type="button" class="wrapbtn">Click to Wrap</button> |
Output
This is my paragraph.
You have to click the button given above to wrap the specified element. The above example showing the div element that also adds some CSS to the wrapped element.
Use Function to Wrap Selected Element
You can also use the function to wrap the selected element. However, the function is the optional parameter to specify. Use the below example to wrap the element with the function.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<script> $(document).ready(function(){ $('.wrapfnbtn').click(function(){ $("p").wrap(function(){ return "<div></div>" }); }); }); </script> <style> div{ background:green; color:#fff; border:1px solid #000; padding:10px; } </style> <p>This is my paragraph.</p><br><br> <button type="button" class="wrapfnbtn">Click to Wrap Using Function</button> |
Output
This is my paragraph.
The above example using the click event to wrap the element. When you click the button given above, the div element got wrapped around the paragraph element.
You may also like to read
I hope you like this tutorial on jQuery wrap() method. If you have any queries regarding the tutorial, please comment below.
References