How to swap DOM child nodes in JavaScript?

Myforwik picture Myforwik · Mar 16, 2012 · Viewed 37.4k times · Source

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

jfriend00 picture jfriend00 · Mar 16, 2012

There is no need for cloning. You can just move one node before the other with this:

childNode[4].parentNode.insertBefore(childNode[4], childNode[3]);

You get the parent of the node. You then call the insertBefore method on the parent and you pass it the childNode[4] node and tell it you want it inserted before childNode[3]. That will give you the result of swapping their order so 4 will be before 3 when it's done.

Reference documentation on insertBefore.

Any node that is inserted into the DOM that is already in the DOM is first removed automatically and then inserted back so there is no need to manually remove it first.