问题描述
是否有方便的方法来“触摸” DOM元素? 我想删除该元素,然后将其再次插入相同位置。 像这样:
element.parentNode.removeChild(element).appendChild(element);
除了appendChild将该元素作为最后一个同级插入。
1楼
drawnonward
2
已采纳
2010-07-02 06:16:04
使用代替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楼
Anurag
2
2010-07-02 08:52:26
这将创建一个虚拟文本节点用作标记,并将其替换为该节点。 稍后,当要重新插入该节点时,将其替换为虚拟节点,以便保留位置。
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楼
John
1
2010-07-02 06:24:14
是的,但是使用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”,然后随时将其插入文档中。