jQuery wrapInner() Method
The wrapInner() method in jQuery is used to wrap the content (inner HTML) of each matched element with an HTML structure or a specified element. It wraps the HTML content inside each selected element with an HTML structure or a new element.
Difference between wrap(), wrapAll(), and wrapInner() methods −
Following table describes the difference between them:
| Method | Difference |
|---|---|
| wrap() | Wraps each selected element individually. |
| wrapAll() | Wraps all selected elements with one wrapper. |
| wrapInner() | Wraps inner content of each selected element. |
Syntax
Following is the syntax o wrapInner() method in jQuery −
$(selector).wrapInner(wrappingElement,function(index))
Parameters
This method accepts the following parameters −
- wrappingElement: Specifies the HTML element(s) to wrap around the inner content of the selected element(s). The possible values could be:
- HTML elements
- DOM elements
- jQuery objects
Example 1
Using wrap() method with HTML element:
In the following example, we are using the wrap() method to wrap a <b> element around the content inside the <div> element (which consists of two <p> elements) −
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$("div").wrapInner("<b></b>");
})
});
</script>
</head>
<body>
<div class="container">
<p>Paragraph element 1.</p>
<p>Paragraph element 2.</p>
</div>
<button>Click me</button>
</body>
</html>
When we execute and click on the button, the two <p> elements inside the <div> element will be wrapped with <b> element.
Example 2
Using wrap() method with DOM element:
In this example, we are passing a DOM element as an argument to wrap() method to wrap a <b> element around the content inside the <div> element −
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$(".container").wrapInner(document.createElement('b'));
})
});
</script>
</head>
<body>
<div class="container">
<p>Paragraph element 1.</p>
<p>Paragraph element 2.</p>
</div>
<button>Click Me</button>
</body>
</html>
When we execute and click on the button, the two <p> elements inside the <div> element will be wrapped with <b> element.
Example 3
Using wrap() method with jQuery element:
Here, we are passing a jQuery object as an argument to wrap() method to wrap the selected elements with the <b> element −
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$(".container").wrapInner($("<b></b>"));
})
});
</script>
</head>
<body>
<div class="container">
<p>Paragraph element 1.</p>
<p>Paragraph element 2.</p>
</div>
<button>Click Me</button>
</body>
</html>
After executing the above program, the two <p> elements inside the <div> element will be wrapped with <b> element.