简体   繁体   中英

Moving a div from inside one div to another div

How do I move the contents of a div to the contents of another div?

I want to move .sidebar from .post to .carousel. How to do it by using javascript?

I want to go from this:

<div class="container">
  <div class="carousel">
    <div class="row">
      <div class="post">
    <div class="sidebar"></div>
      </div>
</div>
  </div>
</div>

to this:

<div class="container">
  <div class="carousel">
    <div class="row">
      <div class="post"></div>
      <div class="sidebar"></div>
    </div>
  </div>
</div>
document.getElementsByClassName('row')[0].appendChild(document.getElementsByClassName('sidebar')[0]);

Assuming you only have only one such occurrence, you can use plain JavaScript:

var sidebar = document.getElementsByClassName('sidebar')[0];

// move after parent node
sidebar.parentNode.parentNode.appendChild(sidebar);

The appendChild() function moves rather than copies existing elements from their previous location in the tree. To perform a copy you would need to clone the respective elements first.

I'd suggest, on the off-chance you've more than one element with that class (and assuming that in all instances they should be inserted after their parentNode ):

$('.sidebar').each(function(){
    $(this).insertAfter(this.parentNode);
});

JS Fiddle demo .

References:

Try to use JQuery Draggable() and Droppable() functions. See the Demo...

Droppable | JQuery UI

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM