Dalibor
Dalibor

Reputation: 11

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>

Upvotes: 1

Views: 810

Answers (4)

earthmover
earthmover

Reputation: 4525

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

Droppable | JQuery UI

Upvotes: 0

bjb568
bjb568

Reputation: 11498

document.getElementsByClassName('row')[0].appendChild(document.getElementsByClassName('sidebar')[0]);

Upvotes: 3

Ja͢ck
Ja͢ck

Reputation: 173652

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.

Upvotes: 1

David Thomas
David Thomas

Reputation: 253486

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:

Upvotes: 1

Related Questions