使用Javascript在DOM中移动类div?

时间:2015-01-26 15:37:22

标签: javascript dom

我正在尝试将一个div(即“topbar”)从其容器中移出一个带有id的div(即“body”)。这可以通过JavaScript实现吗?

没有运气就尝试过这样的事情:

  document.getElementsByClassName('topbar').appendChild(document.getElementsById('body'));

更新问题以便更好地理解。我想将topbar移动到body div之上。

html:

<div id="body"> 
<div class="random"> </div> 
<div class="random"> </div> 
<div class="topbar"> </div> 
</div> 

2 个答案:

答案 0 :(得分:1)

这样的事情?

&#13;
&#13;
var container = document.getElementById('container');
var content1 = document.getElementById('content1');
var subContainer = document.getElementById('subContainer');
var body = document.body;
var content2 = document.getElementById('content2');
container.insertBefore(content1, subContainer);
body.insertBefore(content2, container);
&#13;
#container {
    padding:10px;
    background-color: lightgray;
}
#subContainer {
    border: 1px solid black;
    background-color: gray;
}
&#13;
<body>
  <div id="container">
    <div id="subContainer">
      <div id="content1">
        Content 1 here blah blah blah
      </div>
      <div id="content2">
        Content 2 here blah blah blah
      </div>
      <div id="content3">
        Content 3 here blah blah blah
      </div>
    </div>
  </div>
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

看起来你试图将topbar元素直接移动到类body之前和元素insertBefore()。这可以使用window.onload = function () { //find the element to insert before and then get its parent element var beforeElement = document.getElementById('body'); var parentElement = beforeElement.parentNode; //find the element we want to move //you need the array syntax because 'getElementsByClassName' returns an array of matching elements (even if there is only one match) var moveElement = document.getElementsByClassName('topbar')[0]; //insert the moveElement into the parentElement before the theFirstChild parentElement.insertBefore(moveElement, beforeElement); }; 方法实现:JSFIDDLE DEMO

window.onload = function () { ...script goes here... };



注意:,因为此代码访问和操作DOM,您需要将整个块包装在{{1}}中以确保在脚本运行之前已加载DOM。

insertBefore() method reference