What's the difference between jQuery .wrap and .wrapAll? They pretty much do the same thing, but what could be the difference?
2
-
3If you're smart enough to write, you're probably smart enough to read. Here you go: api.jquery.com/wrap api.jquery.com/wrapAll – ahren Aug 14 '12 at 5:46
-
just even rather keen – Barney Szabolcs May 6 '13 at 9:10
Add a comment
|
Notice the difference in the descriptions:
.wrap()
: Wrap an HTML structure around each element in the set of matched elements..wrapAll()
: Wrap an HTML structure around all elements in the set of matched elements.
.wrap()
wraps every element individually, but .wrapAll()
wraps all of them as a group.
For example:
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
With $('.foo').wrap('<div class="bar" />');
, this happens:
<div class="bar"><div class="foo"></div></div>
<div class="bar"><div class="foo"></div></div>
<div class="bar"><div class="foo"></div></div>
But with $('.foo').wrapAll('<div class="bar" />');
, this happens:
<div class="bar">
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
</div>
WrapAll wraps ALL elements, Wrap wraps EACH element.
$('.inner').wrapAll('<div class="new" />');
Results in wrapping ALL inner-divs in one new div
<div class="container">
<div class="new">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
</div>
Wrap results in ... EACH element
<div class="container">
<div class="new">
<div class="inner">Hello</div>
</div>
<div class="new">
<div class="inner">Goodbye</div>
</div>
</div>
Adding jquery to execute a wrap:
$(‘p’).wrap(‘<span class=”newclass” />’);
will result in:
<span class=”newclass”>
<p>This is a paragraph.</p>
</span>
<span class=”newclass”>
<p>This is a paragraph.</p>
</span>
<span class=”newclass”>
<p>This is a paragraph.</p>
</span>
Substitute the .wrap for .wrapAll.
$(‘p’).wrapAll(‘<span class=”newclass” />’);
will result in:
<span class=”newclass”>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</span>
Now try out .wrapInner.
$(‘p’).wrapInner(‘<span class=”newclass” />’);
will result in:
<p><span class=”newclass”>This is a paragraph.</span></p>
<p><span class=”newclass”>This is a paragraph.</span></p>
<p><span class=”newclass”>This is a paragraph.</span></p>