23 lines
634 B
TypeScript
Raw Normal View History

2019-04-19 13:50:52 +00:00
// swapElements assumes that both elements have valid parent nodes.
2018-04-02 05:34:16 +00:00
export function swapElements(a: Node, b: Node) {
2019-04-19 13:50:52 +00:00
let bParent = b.parentNode as Node
2018-04-02 05:34:16 +00:00
let bNext = b.nextSibling
// Special case for when a is the next sibling of b
if(bNext === a) {
// Just put a before b
2019-04-19 13:50:52 +00:00
bParent.insertBefore(a, b)
2018-04-02 05:34:16 +00:00
} else {
// Insert b right before a
2019-04-19 13:50:52 +00:00
(a.parentNode as Node).insertBefore(b, a)
2018-04-02 05:34:16 +00: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 13:50:52 +00:00
bParent.insertBefore(a, bNext)
2018-04-02 05:34:16 +00:00
} else {
// Otherwise just append it as the last child
2019-04-19 13:50:52 +00:00
bParent.appendChild(a)
2018-04-02 05:34:16 +00:00
}
}
}