What is the easiest way to swap the order of child nodes?
For example I want childNode[3] to be childNode[4] and vice-versa.
Answer by jfriend00 does not really swap elements (it "swaps" only elements which are next to each other and only under the same parent node). This is ok, since this was the question.
This example swaps elements by cloning it but regardless of their position and DOM level:
// Note: Cloned copy of element1 will be returned to get a new reference back
function exchangeElements(element1, element2)
{
var clonedElement1 = element1.cloneNode(true);
var clonedElement2 = element2.cloneNode(true);
element2.parentNode.replaceChild(clonedElement1, element2);
element1.parentNode.replaceChild(clonedElement2, element1);
return clonedElement1;
}
Edit: Added return of new reference (if you want to keep the reference, e. g. to access attribute "parentNode" (otherwise it gets lost)). Example: e1 = exchangeElements(e1, e2);
For a real Swap of any nodes without cloneNode:
<div id="d1">D1</div>
<div id="d2">D2</div>
<div id="d3">D3</div>
With SwapNode function (using PrototypeJS):
function SwapNode(N1, N2) {
N1 = $(N1);
N2 = $(N2);
if (N1 && N2) {
var P1 = N1.parentNode;
var T1 = document.createElement("span");
P1.insertBefore(T1, N1);
var P2 = N2.parentNode;
var T2 = document.createElement("span");
P2.insertBefore(T2, N2);
P1.insertBefore(N2, T1);
P2.insertBefore(N1, T2);
P1.removeChild(T1);
P2.removeChild(T2);
}
}
SwapNode('d1', 'd2');
SwapNode('d2', 'd3');
Will produce:
<div id="d3">D3</div>
<div id="d1">D1</div>
<div id="d2">D2</div>