Daniel Bisceanu
Daniel Bisceanu

Reputation: 1217

move an element from a div to another div

Let's assume that I have this structure

 <div class="firstDiv">
  <div class="insideDiv"></div>
 </div>
 <div class="secondDiv"></div>
 <div class="thirdDiv"></div>

How can I move the .insideDiv from the .firstDiv to the .thirdDiv but going through the .secondDiv ?

I need just a hint or an idea. Thank you!

Upvotes: 1

Views: 7916

Answers (2)

Erijk
Erijk

Reputation: 420

In vanilla JS, it works like this:

var moveIt = function() {
  var outerDiv = document.getElementsByClassName('insideDiv')[0].parentElement;
  var innerDiv = document.getElementsByClassName('insideDiv')[0];

  if (outerDiv.nextElementSibling != null) {
    outerDiv.nextElementSibling.appendChild(outerDiv.removeChild(innerDiv));
  }
}
.firstDiv {
  background-color: yellow
}

.secondDiv {
  background-color: lightblue
}

.thirdDiv {
  background-color: lightpink
}
<div class="container">
  <div class="firstDiv">first
    <div class="insideDiv">inside div</div>
  </div>
  <div class="secondDiv">second</div>
  <div class="thirdDiv">third</div>
</div>

<button type="button" onclick="moveIt()">Move it!</button>

OPTIONAL: wrap-around in else statement below, this needs a scope to operate in. (set by div-element of class 'container'), to be added to above if statement.

else { outerDiv.parentElement.firstElementChild.appendChild(outerDiv.removeChild(innerDiv));
  }

You can see a working example here: codepen: move child-element to nextSibling

Upvotes: 5

brianfit
brianfit

Reputation: 1919

If you don't mind using jquery:

   <div class="firstDiv">
      <div class="insideDiv">InsideBaseball</div>
   </div>
   <div class="secondDiv">SecondBase</div>
   <div class="thirdDiv">ThirdBase</div>
     <button id="SwapButton"> Swap! </button>  


<script>

document.getElementById("SwapButton").onclick = function () { 
    var content = $('.insideDiv').html();
    var content2 = $('.thirdDiv').html();
    $('.thirdDiv').replaceWith(content);
    $('.insideDiv').replaceWith(content2);
  };
</script>

Upvotes: 0

Related Questions