-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselector.js
More file actions
45 lines (40 loc) · 1.12 KB
/
selector.js
File metadata and controls
45 lines (40 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
export function getUniqueSelector(element) {
function getElementSelector(element) {
if (element.id) {
return `#${element.id.replace(/:/g, "\\:")}`;
}
let selector = element.tagName.toLowerCase();
if (
element.className instanceof String &&
element.className.trim() !== ""
) {
selector += `.${element.className.replace(/ /g, ".")}`;
}
let siblings = Array.from(element.parentNode.children);
let index = siblings.indexOf(element) + 1;
if (siblings.length > 1) {
selector += `:nth-child(${index})`;
}
return selector;
}
function isUnique(selector) {
let cnt = document.querySelectorAll(selector).length;
if (cnt === 0) {
throw new Error(`No elements found for selector: ${selector}`);
}
return cnt === 1;
}
let selector = getElementSelector(element);
let parent = element.parentElement;
while (parent) {
selector = `${getElementSelector(parent)} > ${selector}`;
parent = parent.parentElement;
if (isUnique(selector)) {
return selector;
}
}
if (isUnique(selector)) {
return selector;
}
return undefined;
}