From 9a66411258781a57d5c953b7113403fdf0d218cf Mon Sep 17 00:00:00 2001 From: Hsieh Chin Fan Date: Thu, 17 Oct 2024 10:31:22 +0800 Subject: feat: add utils for finding common ancestor --- src/utils.mjs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/utils.mjs b/src/utils.mjs index 1fe3ce5..327bee4 100644 --- a/src/utils.mjs +++ b/src/utils.mjs @@ -177,3 +177,35 @@ export const replaceTextNodes = ( node = nodeIterator.nextNode() } } + +/** + * Get the common ancestor of two or more elements + * {@link https://gist.github.com/kieranbarker/cd86310d0782b7c52ce90cd7f45bb3eb} + * @param {String} selector A valid CSS selector + * @returns {Element} The common ancestor + */ +export function getCommonAncestor (selector) { + // Get the elements matching the selector + const elems = document.querySelectorAll(selector) + + // If there are no elements, return null + if (elems.length < 1) return null + + // If there's only one element, return it + if (elems.length < 2) return elems[0] + + // Otherwise, create a new Range + const range = document.createRange() + + // Start at the beginning of the first element + range.setStart(elems[0], 0) + + // Stop at the end of the last element + range.setEnd( + elems[elems.length - 1], + elems[elems.length - 1].childNodes.length, + ) + + // Return the common ancestor + return range.commonAncestorContainer +} -- cgit v1.2.3-70-g09d2