Search code examples
javascriptjquerywrappergettext

How to wrap text inside new div?


My HTML:

<div class="mainDiv">
  <p>This is a paragraph</p>
  <div class="innerDiv">This is a div</div>
  This is what I want to wrap
</div>

What I want:

<div class="mainDiv">
  <p>This is a paragraph</p>
  <div class="innerDiv">This is a div</div>
  <div class="wrapper">
    This is what I want to wrap
  </div>
</div>

I've tried:

$('.mainDiv').find(".innerDiv").next().wrap('<div class="wrapper" />')

but it does not work. How can I achieve above result?


Solution

  • You can use jQuery contents() along with slice method:

    $('.mainDiv').contents().slice(-1).wrap('<div class="wrapper"/>');
    

    Working Demo