Swapping Two Nodes in the DOM
Just came across this post at JavaScript.faqts on How to swap two nodes in the DOM…
IE5+ provides a swapNode method for nodes in a HTML document. W3C DOM as implemented by Mozilla doesn’t provide such a method but the functionality is easy to implement. With Mozilla/NN6 you can prototype such a method for Node objects:
<script type="text/javascript; version=1.5">
Node.prototype.swapNode = function (node) {
var nextSibling = this.nextSibling;
var parentNode = this.parentNode;
node.parentNode.replaceChild(this, node);
parentNode.insertBefore(node, nextSibling);
}
</script>



I’ve tried this method before and it’s not quite as perfect as it sounds - it doesn’t work in all instances and isn’t directly comparable with the IE swapNode function. Don’t ask me why it doesn’t work that well, it looks like it should. Maybe it’s to do with how whitespace and comments are sometimes treated as nodes - dunno.
It requires the calling node to be at a higher position than the node param. If you ensure that, it works fine.