How can I wrap () all the elements in one container, and not every element?

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 P in one container as follows:

<fieldset>
   <legend>Title</legend>

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

Here is my current Javascript:

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

This, however, causes each P element to be wrapped in its own div.container. For instance:

<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 an easier 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>');
   });
});
+3
source share
2 answers

You can use the wrapAll () method.

So something like this.

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

you can also do something like this

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

A good day!

0
source

Source: https://habr.com/ru/post/1753098/


All Articles