The wrap method
The wrap method wraps elements in the given tag.
Syntax
The method parameter can be text (possibly with tags), a DOM element, or a jQuery object:
.wrap(text or tag);
This is how the selected elements are wrapped with the content that will be returned by the custom function. The function is called separately, for each of the selected elements, and takes the position of the element in the set as a parameter:
.wrap(function(number in the set));
Example
Let's wrap all paragraphs with class www with tag div:
<p class="www">text</p>
<p class="www">text</p>
<p class="www">text</p>
<p>text</p>
$('.www').wrap(document.createElement('div'));
HTML the code will look like this:
<div><p class="www">text</p></div>
<div><p class="www">text</p></div>
<div><p class="www">text</p></div>
<p>text</p>
Example
You can pass not only the tag name as a parameter, but also this construction:
<p class="www">text</p>
<p class="www">text</p>
<p class="www">text</p>
<p>text</p>
$('.www').wrap('<div></div>');
HTML the code will look like this:
<div><p class="www">text</p></div>
<div><p class="www">text</p></div>
<div><p class="www">text</p></div>
<p>text</p>
Example
You can write any attributes in the opening tag, and the wrapping will be done with these attributes. Let's wrap paragraphs with the class www in a div with the class zzz:
<p class="www">text</p>
<p class="www">text</p>
<p class="www">text</p>
<p>text</p>
$('.www').wrap('<div class="zzz"></div>');
HTML the code will look like this:
<div class="zzz"><p class="www">text</p></div>
<div class="zzz"><p class="www">text</p></div>
<div class="zzz"><p class="www">text</p></div>
<p>text</p>
See also
-
methods
wrapAll,wrapInner⁅/ c⁆, ⁅c href="/en/javascript/lib/jquery/manual/unwrap/"⁆unwrap,
allowing you to work with wrapping elements