aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--src/utils.mjs32
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 */
187export 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}