How to swap DOM child nodes in JavaScript?

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

    A solution that works without cloning, given the indices of the two elements to swap:

    function swapChildren(parentElement, index1, index2) {
    
        if (index1 === index2)
            return
    
        if (index1 > index2) {
    
            const temp = index1
    
            index1 = index2
            index2 = temp
        }
    
        const { [index1]: element1, [index2]: element2 } = parentElement.childNodes
    
        if (index2 === index1 + 1) {
            parentElement.insertBefore(element2, element1)
        } else {
    
            const reference = element2.nextSibling
    
            parentElement.replaceChild(element2, element1)
            parentElement.insertBefore(element1, reference)
        }
    }
    

提交回复
热议问题