"touch" a DOM element
Is there a handy way to "touch" a DOM element? I'd like to remove the element and insert it again at the same position. Something like this:
element.parentNode.removeChild(element).appendChild(element);
except that appendChild inserts the element as the last s开发者_如何转开发ibling.
Use insertBefore instead of 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);
}
This creates a dummy text node to be used as a marker and replaces it with the node. Later when the node is to be re-inserted, replace it with the dummy node so the position is preserved.
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
Yes but it would be better to use the DOM cloneNode(true) as it would retain all of the child nodes and properties:
// 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);
That is the way that I would do it as you can hold onto the variable "theNewChild" 100% as it was and insert it back into the document at any time.
精彩评论