jQuery: move the complete element into another one, but not its content only

There is the source DIV element that must appear within the target DIV.

And there is jQuery appendTo method that seems to do that for me.

For example:

<div class="source">Move Me</div>
<div class="destination"></div>

jQuery(document).ready(function(){
    jQuery('.source').contents().appendTo('.destination')
  });

But actually it only moves source's content into the target DIV, keeping the empty source DIV where it originally was: here is the JSFiddle that demonstrates this.

So, instead of

<div class="destination">
    <div class="source">Move Me</div>
</div>

the appendTo result is just

<div class="source"></div>
<div class="destination">Move Me</div>

Is there a way to achieve

<div class="destination">
    <div class="source">Move Me</div>
</div>

without extra wrapping elements?

Answers 1

  • $.contents() will grab the content of the element, but leave the element itself alone. The default behavior of $.append() and $.appendTo() is to move the entire element. So in your example, you simply need to use jQuery('.source').appendTo('.destination') and that will move .source in to .destination

    jQuery('.source').appendTo('.destination')
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="source">Move Me</div>
    <div class="destination"></div>


Related Articles