javascriptjquerywrapall

Filter <p> within a div and wrap all


I'm trying to wrap all <p> from a div in a sub-div; the numbers of <p> is not constant.

<div id="page">
  <p>text</p>
  <p>text</p>
  <p>text</p>
</div>

Trying to obtain:

<div id="page">
  <div>
    <p>text</p>
    <p>text</p>
    <p>text</p>
  </div>
</div>

Using:

<script>
 jQuery('#page').filter('p').wrapAll('<div></div>');
</script>

And it's not working.


Solution

  • You can do it using .wrapAll() like this:

    jQuery('#page p').wrapAll('<div></div>');
    

    Or using .wrapInner() like this:

    jQuery('#page').wrapInner('<div></div>');