【问题标题】:"touch" a DOM element“触摸”一个 DOM 元素
【发布时间】:2010-07-02 06:05:17
【问题描述】:

有没有一种方便的方法来“触摸”一个 DOM 元素?我想删除该元素并在同一位置再次插入它。像这样的:

element.parentNode.removeChild(element).appendChild(element);

除了 appendChild 将元素作为最后一个兄弟元素插入。

【问题讨论】:

  • 你希望通过这个实现什么?

标签: javascript dom


【解决方案1】:

使用insertBefore 而不是 appendChild。

var other = element.nextSibling;

if ( other ) {
  other.parentNode.removeChild(element);
  other.parentNode.insertBefore(element,other);
} else {
  other = element.parentNode;
  other.removeChild(element);
  other.appendChild(element);
}

【讨论】:

    【解决方案2】:

    这将创建一个虚拟文本节点用作标记并将其替换为节点。稍后当要重新插入节点时,将其替换为虚拟节点,以便保留位置。

    Node.replaceChild

    var dummy = document.createTextNode('');
    var parent = element.parentNode;
    
    parent.replaceChild(dummy, element); // replace with empty text node
    parent.replaceChild(element, dummy); // swap out empty text node for original
    

    【讨论】:

      【解决方案3】:

      是的,但最好使用 DOM cloneNode(true),因为它会保留所有子节点和属性:

      // Copy the node.
      var theOldChild = document.getElementById("theParent").childNodes[blah]
      var theNewChild = theOldChild.cloneNode(true);
      
      // Find the next Sibling
      var nextSib = theOldChild.nextSibling();
      
      // Remove the old Node
      theOldChild.parentNode.removeChild(theOldChild)
      
      // Append where it was.
      nextSib.parentNode.inserertBefore(theNewChild, nextSib);
      

      我会这样做,因为您可以 100% 保留变量“theNewChild”,并随时将其重新插入到文档中。

      【讨论】:

      • 为什么这样更好?在删除之前将节点保存在变量中也会保存所有子节点,不是吗?
      • 我不相信它会。当您在变量中引用它时,您引用的是元素,而不是结构。另外,这是对现有对象的引用,它不是 HTML 片段,DOM 不应允许您在其他地方重新插入该节点。
      猜你喜欢
      • 2011-12-10
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多