tags:

views:

60

answers:

3

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 sibling.

+2  A: 

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);
}
drawnonward
The best answer so far, accepting.
David
+1  A: 

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.

John
why is this better? Saving a node in a variable before deleting will also save all children, no?
David
I do not believe it does. When you reference it in a variable you are referencing the element, not it's structure. Plus that is a reference to an existing object, It is not an HTML Fragment, the DOM should not allow you to reinsert that node elsewhere.
John
+2  A: 

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
Anurag