How to swap DOM child nodes in JavaScript?

前端 未结 8 1448
时光说笑
时光说笑 2020-12-03 04:29

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.

8条回答
  •  情书的邮戳
    2020-12-03 04:51

    I needed a function to swap two arbitrary nodes keeping the swapped elements in the same place in the dom. For example, if a was in position 2 relative to its parent and b was in position 0 relative to its parent, b should replace position 2 of a's former parent and a should replace child 0 of b's former parent.

    This is my solution which allows the swap to be in completely different parts of the dom. Note that the swap cannot be a simple three step swap. Each of the two elements need to be removed from the dom first because they may have siblings that would need updating, etc.

    Solution: I put in two holder div's to hold the place of each node to keep relative sibling order. I then reinsert each of the nodes in the other's placeholder, keeping the relative position that the swapped node had before the swap. (My solution is similar to Buck's).

    function swapDom(a,b) 
    {
         var aParent = a.parentNode;
         var bParent = b.parentNode;
    
         var aHolder = document.createElement("div");
         var bHolder = document.createElement("div");
    
         aParent.replaceChild(aHolder,a);
         bParent.replaceChild(bHolder,b);
    
         aParent.replaceChild(b,aHolder);
         bParent.replaceChild(a,bHolder);    
    }
    

提交回复
热议问题