How to put one element before another with jQuery?

4

How to make a certain HTML before another div? I tried using prepend but it poe at the beginning inside the div but I want it to put above / before and out of it, using prepend it looks like this:

<div class="pai"><div>FILHO</div></div>

But the correct and necessary for me would be like this:

<div>FILHO</div><div class="pai"></div>

Is it possible with what code?

    
asked by anonymous 27.06.2015 / 00:06

1 answer

5

To remove the div with HTML FILHO from within the div .pai and put the same before from the div .pai you can do so:

Initial HTML:

<div class="pai">
    <div>FILHO</div>
</div>

jQuery:

var pai = $('.pai');
var filho = pai.find('div'); // vai buscar a div que tem HTML filho
filho.insertBefore(pai); // inserir div que tem HTML filho antes da div .pai

Final HTML:

<div>FILHO</div>
<div class="pai"></div>

jsFiddle: link

    
27.06.2015 / 00:11