How to swap DOM child nodes in JavaScript?

前端 未结 8 1437
时光说笑
时光说笑 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 05:05

    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);

提交回复
热议问题