Search code examples
javascriptjqueryinsertafter

Use insertAfter with child elements


just a quick one. I want to change the order of two specific divs in the markup. Both divs have childs.

<div class="first">
  <elem>
    <elem> </elem>
  </elem>
</div>

<div class="second">
  <elem>
     <elem> </elem>
  <elem>
</div>

and want it to change to .second then .first.

I tried:

$('.first').insertAfter('.second');

which works, but without the childs. Is there any way to achieve what I want with .insertAfter() or is there anything else I need to do?

Thanks


Solution

  • Insert after doesn't remove children elements, check this fiddle

    <div class="first">
        <div>child of first</div>
        <div>another of first</div>
    </div>
    
    <div class="second">
        <div>child of second</div>
    </div>