Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  180] [ 1]  / answers: 1 / hits: 52877  / 12 Years ago, fri, march 16, 2012, 12:00:00

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.


More From » dom

 Answers
25

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.


[#86806] Thursday, March 15, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
briarc

Total Points: 402
Total Questions: 85
Total Answers: 114

Location: El Salvador
Member since Sun, Sep 12, 2021
3 Years ago
;