当前位置: 代码迷 >> JavaScript >> “触摸” DOM元素
  详细解决方案

“触摸” DOM元素

热度:9   发布时间:2023-06-03 17:55:25.0

是否有方便的方法来“触摸” DOM元素? 我想删除该元素,然后将其再次插入相同位置。 像这样:

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

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

使用代替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);
}

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

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

是的,但是使用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”,然后随时将其插入文档中。

  相关解决方案