将元素从div移动到另一个div

时间:2018-02-22 17:23:37

标签: javascript html css

我们假设我有这个结构

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

如何将.insideDiv.firstDiv移至.thirdDiv但是经过.secondDiv

我只需要一个提示或想法。谢谢!

2 个答案:

答案 0 :(得分:1)

在vanilla JS中,它的工作原理如下:

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>

可选:在下面的else语句中进行环绕,这需要一个操作范围。(由类'container'的div-element设置),将被添加到上面的if语句中。

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

您可以在此处查看一个有效的示例:codepen: move child-element to nextSibling

答案 1 :(得分:0)

如果你不介意使用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>

<强>