Skip to content

Instantly share code, notes, and snippets.

@souporserious
Last active February 1, 2024 19:28
Show Gist options
  • Save souporserious/d8f6701426c8e331792c0c99635d2bfa to your computer and use it in GitHub Desktop.
Save souporserious/d8f6701426c8e331792c0c99635d2bfa to your computer and use it in GitHub Desktop.
/** Get the offset ancestors of a node. */
function getOffsetAncestors(node: HTMLElement): Set<HTMLElement> {
let ancestors = new Set<HTMLElement>()
let current: Element | null = node.offsetParent
while (current) {
if (current instanceof HTMLElement) {
ancestors.add(current)
current = current.offsetParent
} else {
break
}
}
return ancestors
}
/** Find the common offset parent of a set of nodes. */
function findCommonOffsetParent(nodes: HTMLElement[] = []): HTMLElement {
let commonAncestors = getOffsetAncestors(nodes[0])
for (let index = 1; index < nodes.length; index++) {
const ancestors = getOffsetAncestors(nodes[index])
for (let ancestor of commonAncestors) {
if (!ancestors.has(ancestor)) {
commonAncestors.delete(ancestor)
}
}
if (commonAncestors.size === 0) {
return document.body
}
}
return commonAncestors.size > 0
? commonAncestors.values().next().value
: document.body
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment