开发者

How can I wrap() all elements in one container rather than each element?

开发者 https://www.devze.com 2023-01-05 22:02 出处:网络
I have HTML similar to the following: <fieldset> <legend>Title</legend> <p>blahblahblah</p>

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 开发者_JAVA百科rather than using something like:

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


You can use the wrapAll() method.

So something like this.

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


you can also do something like this

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

Have a Good Day !!

0

精彩评论

暂无评论...
验证码 换一张
取 消