Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between jQuery wrap and wrapAll

Tags:

jquery

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

like image 939
nasty Avatar asked Aug 14 '12 05:08

nasty


2 Answers

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>
like image 193
Blender Avatar answered Oct 23 '22 06:10

Blender


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>
like image 20
Yoeri Avatar answered Oct 23 '22 05:10

Yoeri