Skip to content
Advertisement

How to swap DOM child nodes in JavaScript?

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.

Advertisement

Answer

There is no need for cloning. You can just move one node before the other. The .insertBefore() method will take it from its current location and insert it somewhere else (thus moving it):

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement