app-walkthrough
Version:
An intuitive guided walkthrough library with UI highlighting and voice narration for web apps.
43 lines (42 loc) • 1.31 kB
JavaScript
export function getSelectors(element) {
const selectors = [];
if (!element)
return selectors;
// ID selector (most specific)
if (element.id) {
selectors.push(`#${element.id}`);
}
// data-test attributes
for (const attr of Array.from(element.attributes)) {
if (attr.name.startsWith("data-test")) {
selectors.push(`[${attr.name}="${attr.value}"]`);
}
}
// ARIA role selector
const role = element.getAttribute("role");
if (role) {
selectors.push(`${element.tagName.toLowerCase()}[role="${role}"]`);
}
// Build structural path selector
const path = [];
let current = element;
while (current && current.parentElement) {
const tagName = current.tagName.toLowerCase();
let nth = 1;
let sibling = current.previousElementSibling;
while (sibling) {
if (sibling.tagName === current.tagName) {
nth++;
}
sibling = sibling.previousElementSibling;
}
if (tagName !== "html" && tagName !== "body") {
path.unshift(`${tagName}:nth-of-type(${nth})`);
}
current = current.parentElement;
}
if (path.length) {
selectors.push(path.join(" > "));
}
return selectors;
}