nasty nasty - 2 days ago 4
jQuery Question

Difference between jQuery wrap and wrapAll

What's the difference between jQuery .wrap and .wrapAll? They pretty much do the same thing, but what could be the difference?

Answer

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>