
jQuery wrapInner() method
The jQuery wrapInner()
method is used to wrap the content (child elements) of each selected element with an HTML structure. It allows you to add a wrapping element around the content of the selected elements, without altering the selected elements themselves.
The syntax for using the wrapInner()
method is as follows:
$(selector).wrapInner(wrappingElement);
selector
: It is a string that specifies the elements to be selected.wrappingElement
: It can be an HTML string, a DOM element, or a jQuery object that represents the wrapping element you want to add around the content of the selected elements.
Here’s an example of how you can use the wrapInner()
method:
HTML:
<div class="box">
<p>This is some text inside the box.</p>
</div>
<div class="box">
<p>This is another paragraph inside another box.</p>
</div>
JavaScript:
// Wrap the content of each box div with a span element
$('.box').wrapInner('<span class="wrapper"></span>');
After executing the above JavaScript code, the content (child elements) of each div
element with the class “box” will be wrapped with a span
element with the class “wrapper”:
Resulting HTML:
<div class="box">
<span class="wrapper">
<p>This is some text inside the box.</p>
</span>
</div>
<div class="box">
<span class="wrapper">
<p>This is another paragraph inside another box.</p>
</span>
</div>
The wrapInner()
method is particularly useful when you want to add a common structure to the content of multiple elements without changing the elements themselves. It is commonly used for styling or adding functionality to the content inside selected elements.
Keep in mind that the wrapInner()
method wraps the content of each selected element individually, without cloning or duplicating the original content. If you need to clone the content before wrapping, you can use the wrapAll()
method instead. Additionally, if you want to wrap the selected elements themselves, you can use the wrap()
method.