Turbodurso
Turbodurso

Reputation: 61

How to use .wrapAll() in jQuery?

I need to find all the p tags inside all the divs with a class of someClass and wrap them with another div. This is how the beginning mark up would look like:

<div class="someClass">
  // Lots of different tags generated by the site
  <p>Some text</p>
  <p>Some text</p>
  <p>Some text</p>
  <p>Some text</p>
</div>

<div class="someClass">
  // Lots of different tags generated by the site
  <p>Some text</p>
  <p>Some text</p>
</div>

Would turn into:

<div class="someClass">
  // Lots of different tags generated by the site
  <div class="bla">
    <p>Some text</p>
    <p>Some text</p>
    <p>Some text</p>
    <p>Some text</p>
  </div>
</div>

<div class="someClass">
  // Lots of different tags generated by the site
  <div class="bla">
    <p>Some text</p>
    <p>Some text</p>
  </div>
</div>

Any ideas? When I try using .each(): for each div with a class of someClass wrap all the p tags, but it just wraps them all together in the top div.

Upvotes: 3

Views: 1516

Answers (1)

John Fisher
John Fisher

Reputation: 22717

Have you tried this?

$('div.someClass p').wrapAll(...);

Or this?

$('div.someClass').each(function() {
  $(this).find('p').wrapAll(...);
});

Edit

After looking at the code you posted, it appears to be a syntax issue. You need quotes in this line:

$(this).find('p').wrapAll(<div class='toggle'></div>);

It should be:

$(this).find('p').wrapAll("<div class='toggle'></div>");

Upvotes: 3

Related Questions