【发布时间】:2014-07-16 17:25:02
【问题描述】:
function rearrange(x, y) {
x.parentNode.replaceChild(x, y);
x.parentNode.insertBefore(y,x);
}
如果我这样做了
var a = document.getElementsByClassName('btn-button-google')[0];
var b = document.getElementsByClassName('btn-button-doodle')[0];
rearrange(b,a);
我收到以下错误
NotFoundError: Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node.
我理解,因为 a 在一个 html div 中,而 b 在另一个 div 中,但我很好奇如何解决这个问题。这行得通
rearrange(b.parentNode,a.parentNode);
因为它们在同一个节点中。
示例 HTML
<div class="container">
<div class="group">
<a href="" class="btn-button-bold"><a>
<a href="" class="btn-button-italic"><a>
<a href="" class="btn-button-strike"><a>
</div>
<div class="group">
<a href="" class="btn-button-font"><a>
<a href="" class="btn-button-ffamily"><a>
<a href="" class="btn-button-google"><a>
</div>
<div class="group">
<a href="" class="btn-button-smilies"><a>
<a href="" class="btn-button-doodle"><a>
<a href="" class="btn-button-source"><a>
</div>
</div>
【问题讨论】:
-
x.parentNode.replaceChild(y, x);MDNreplaceChild -
好吧,我试一试
-
但是,如果
x需要代替y,您需要先获取y的父级和下一个兄弟级,然后再移动它,以便您拥有地点x的参考点。 -
...另外,我在您的 HTML 中没有看到
btn-button-doodle。 -
应该是
var yPar = y.parentNode, ySib = y.nextSibling; x.parentNode.replaceChild(y, x); yPar.insertBefore(x, ySib);当我们移动y时,我们忘记了它的原始位置。所以我们在移动之前引用它。
标签: javascript html html-manipulation