diff options
| author | Hsieh Chin Fan <pham@topo.tw> | 2024-10-17 10:31:22 +0800 |
|---|---|---|
| committer | Hsieh Chin Fan <pham@topo.tw> | 2024-10-17 10:31:38 +0800 |
| commit | 9a66411258781a57d5c953b7113403fdf0d218cf (patch) | |
| tree | 7a9c02421b33dcb36460acceed381d4a116c148d /src | |
| parent | 5b1e0f50415fd7834b467e18859c0bd789c646a9 (diff) | |
feat: add utils for finding common ancestor
Diffstat (limited to 'src')
| -rw-r--r-- | src/utils.mjs | 32 |
1 files changed, 32 insertions, 0 deletions
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 = ( | |||
| 177 | node = nodeIterator.nextNode() | 177 | node = nodeIterator.nextNode() |
| 178 | } | 178 | } |
| 179 | } | 179 | } |
| 180 | |||
| 181 | /** | ||
| 182 | * Get the common ancestor of two or more elements | ||
| 183 | * {@link https://gist.github.com/kieranbarker/cd86310d0782b7c52ce90cd7f45bb3eb} | ||
| 184 | * @param {String} selector A valid CSS selector | ||
| 185 | * @returns {Element} The common ancestor | ||
| 186 | */ | ||
| 187 | export function getCommonAncestor (selector) { | ||
| 188 | // Get the elements matching the selector | ||
| 189 | const elems = document.querySelectorAll(selector) | ||
| 190 | |||
| 191 | // If there are no elements, return null | ||
| 192 | if (elems.length < 1) return null | ||
| 193 | |||
| 194 | // If there's only one element, return it | ||
| 195 | if (elems.length < 2) return elems[0] | ||
| 196 | |||
| 197 | // Otherwise, create a new Range | ||
| 198 | const range = document.createRange() | ||
| 199 | |||
| 200 | // Start at the beginning of the first element | ||
| 201 | range.setStart(elems[0], 0) | ||
| 202 | |||
| 203 | // Stop at the end of the last element | ||
| 204 | range.setEnd( | ||
| 205 | elems[elems.length - 1], | ||
| 206 | elems[elems.length - 1].childNodes.length, | ||
| 207 | ) | ||
| 208 | |||
| 209 | // Return the common ancestor | ||
| 210 | return range.commonAncestorContainer | ||
| 211 | } | ||