Added null checks

This commit is contained in:
2019-04-19 22:50:52 +09:00
parent 707233a422
commit d16197340d
8 changed files with 31 additions and 18 deletions

View File

@ -1,22 +1,23 @@
// swapElements assumes that both elements have valid parent nodes.
export function swapElements(a: Node, b: Node) {
let parent = b.parentNode
let bParent = b.parentNode as Node
let bNext = b.nextSibling
// Special case for when a is the next sibling of b
if(bNext === a) {
// Just put a before b
parent.insertBefore(a, b)
bParent.insertBefore(a, b)
} else {
// Insert b right before a
a.parentNode.insertBefore(b, a)
(a.parentNode as Node).insertBefore(b, a)
// Now insert a where b was
if(bNext) {
// If there was an element after b, then insert a right before that
parent.insertBefore(a, bNext)
bParent.insertBefore(a, bNext)
} else {
// Otherwise just append it as the last child
parent.appendChild(a)
bParent.appendChild(a)
}
}
}