How to put one element before another with jQuery?

Asked

Viewed 3,035 times

4

How to make a certain HTML before another div? I tried using prepend but it puts at first into the div but I want it to put up/before and outside of it, using prepend she gets like this:

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

but the right and necessary for me would be so:

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

is possible with which code?

  • 1

    And what is the initial HTML?

  • @Sergio the job would have to be done on top of the div $(".pai")...

1 answer

5


To remove the div with HTML FILHO from inside the div .pai and put the same before of the div .pai you can do it like this:

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

HTML final:

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

jsFiddle: http://jsfiddle.net/6717y46x/

  • I didn’t know about this function.. But if I happen to be getting html and it doesn’t exist yet on the page, how would I do it? Like I’m getting an html from an ajax and I want to put it in front of the .pai.. The same way it was made..

  • 1

    @user3163662 puts this HTML in a variable like here var filho = pai.find('div'); and the rest is the same. If it comes from ajax you can for example do var filho = 'string com html aqui'; and use the rest the same.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.