代码之家  ›  专栏  ›  技术社区  ›  David Hellsing

“touch”DOM元素

  •  0
  • David Hellsing  · 技术社区  · 16 年前

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

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

    除了appendChild插入元素作为最后一个同级元素。

    3 回复  |  直到 16 年前
        1
  •  2
  •   drawnonward    16 年前

    insertBefore 而不是孩子。

    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
  •  2
  •   Anurag    16 年前

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

    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
  •  1
  •   John    16 年前

    是的,但最好使用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);
    

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