Use insertAfter with child elements

124 Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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>
0
On

The documentation says "If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved after the target (not cloned) and a new set consisting of the inserted element is returned"

In the simplest case (select by id - insert after div with a given id), my tests show that all the children come along with it.