【问题标题】:Rearranging elements with a simple function用简单的功能重新排列元素
【发布时间】: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); MDN replaceChild
  • 好吧,我试一试
  • 但是,如果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


【解决方案1】:

.replaceChild 方法接受替换作为第一个参数,将要替换的子项作为第二个参数。你把它们颠倒了,这导致了错误。

此外,如果意图是交换,你需要持有对y的原始位置的引用,因为一旦你移动它,它就会被遗忘。

这适用于大多数情况:

var yPar = y.parentNode, ySib = y.nextSibling; 
x.parentNode.replaceChild(y, x); 
yPar.insertBefore(x, ySib);

请注意,还有一个问题需要考虑。只要两个节点有不同的父节点就没有问题,但是如果共享一个父节点,并且彼此相邻,并且缓存的nextSiblingx相同,那么它就会有没有效果。因此,如果可能,您需要对此进行测试,并处理这种特殊情况。

【讨论】:

    猜你喜欢
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 2011-05-04
    • 2016-08-31
    • 2012-06-11
    相关资源
    最近更新 更多