24 lines
647 B
TypeScript
Raw Normal View History

2019-04-19 22:50:52 +09:00
// swapElements assumes that both elements have valid parent nodes.
2019-11-18 11:04:13 +09:00
export default function swapElements(a: Node, b: Node) {
2019-11-17 18:25:14 +09:00
const bParent = b.parentNode as Node
const bNext = b.nextSibling
2018-04-02 07:34:16 +02:00
// Special case for when a is the next sibling of b
if(bNext === a) {
// Just put a before b
2019-04-19 22:50:52 +09:00
bParent.insertBefore(a, b)
2018-04-02 07:34:16 +02:00
} else {
// Insert b right before a
2019-04-19 22:50:52 +09:00
(a.parentNode as Node).insertBefore(b, a)
2018-04-02 07:34:16 +02:00
// Now insert a where b was
if(bNext) {
// If there was an element after b, then insert a right before that
2019-04-19 22:50:52 +09:00
bParent.insertBefore(a, bNext)
2018-04-02 07:34:16 +02:00
} else {
// Otherwise just append it as the last child
2019-04-19 22:50:52 +09:00
bParent.appendChild(a)
2018-04-02 07:34:16 +02:00
}
}
2019-11-17 18:44:30 +09:00
}