astro-vtbot
Version:
The 👜 Bag of Tricks ✨ for Astro's View Transitions
24 lines (23 loc) • 664 B
text/typescript
export function deriveCSSSelector(element?: Element, useIds = true) {
let path: string[] = [];
while (element && element.nodeType === Node.ELEMENT_NODE) {
let selector = element.nodeName.toLowerCase();
if (useIds && element.id) {
selector = '#' + element.id;
path.unshift(selector);
break;
} else {
let sibling = element;
let nth = 1;
while ((sibling = sibling.previousElementSibling as Element)) {
if (sibling.nodeName.toLowerCase() === selector) nth++;
}
if (nth !== 1) {
selector += ':nth-of-type(' + nth + ')';
}
}
path.unshift(selector);
element = element.parentNode as Element;
}
return path.join(' > ');
}