我们假设我有这个结构
<div class="firstDiv">
<div class="insideDiv"></div>
</div>
<div class="secondDiv"></div>
<div class="thirdDiv"></div>
如何将.insideDiv
从.firstDiv
移至.thirdDiv
但是经过.secondDiv
?
我只需要一个提示或想法。谢谢!
答案 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>