views:

66

answers:

2

I have HTML similar to the following:

<fieldset>
   <legend>Title</legend>

   <p>blahblahblah</p>
   <p>blahblahblah</p>
   <p>blahblahblah</p>
</fieldset>

What I want to do is wrap all the P's into a single container like so:

<fieldset>
   <legend>Title</legend>

   <div class="container">
      <p>blahblahblah</p>
      <p>blahblahblah</p>
      <p>blahblahblah</p>
   </div>
</fieldset>

Here's my current Javascript:

$(document).ready(function()
{
   $('fieldset legend').click(function()
   {
      $(this).siblings().wrap('<div class="container"></div>');
   });
});

That, however, causes each P element to be wrapped in it's own div.container. Like so:

<fieldset>
   <legend>Title</legend>

   <div class="container"><p>blahblahblah</p></div>
   <div class="container"><p>blahblahblah</p></div>
   <div class="container"><p>blahblahblah</p></div>
</fieldset>

Is there a neater way to accomplish this rather than using something like:

$(document).ready(function()
{
   $('fieldset legend').click(function()
   {
      $(this).after('<div class="container"></div>');
      $(this).parent().append('</div>');
   });
});
+7  A: 

You can use the wrapAll() method.

So something like this.

$("fieldset").children("p").wrapAll('<div class="container"></div>');
Marko
Completely forgot about that function :/ Cheers.
Greg
Here's a fiddle http://jsfiddle.net/AmUxm/
Marko
No problems - please mark as correct if this answered your question :) Cheers
Marko
+1  A: 

you can also do something like this

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

Have a Good Day !!

Ninja Dude