How to swap DOM child nodes in JavaScript?

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

    Try this method:

    1. Get the parent element
    2. Store the two elements you want to swap
    3. Store the .nextSibling of the node that is last in order eg: [1,2,3,4] => we want to swap 3 & 2 then store nextSibling of 3, '4'.

    4. .insertBefore(3,2);

    5. .insertBefore(2,nextSibling);

提交回复
热议问题