-
Notifications
You must be signed in to change notification settings - Fork 2
/
xpath2.js
96 lines (90 loc) · 2.86 KB
/
xpath2.js
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
class XPath2 {
static getElementPath(element, topParent = null) {
let path = [];
if (topParent) {
if (typeof topParent == "string") {
topParent = document.querySelector(topParent);
} else if (parent instanceof HTMLElement) {
topParent = parent;
}
}
while (element) {
path.unshift(element);
if (topParent && topParent == element) {
break;
}
element = element.parentElement;
}
return path;
}
static getElementXPathIdentifier(element) {
let id = element.tagName.toLowerCase();
if (element.parentElement) {
let tagSiblings = element.parentElement.querySelectorAll(":scope > " + element.tagName);
if (tagSiblings.length > 1) {
let index = Array.from(tagSiblings).indexOf(element);
id += "[" + (index + 1) + "]";
}
}
return id;
}
static getElementXPath(element, topParent = null) {
let xpath = [];
let parents = XPath2.getElementPath(element, topParent);
if (topParent) {
parents.shift();
}
parents.forEach(parent => {
xpath.push(XPath2.getElementXPathIdentifier(parent));
});
xpath = xpath.join("/");
if (!topParent) {
xpath = "/" + xpath;
}
return xpath;
}
static getElementByXPath(xpath, topParent = null) {
if (topParent) {
if (typeof topParent == "string") {
topParent = document.querySelector(topParent);
} else if (parent instanceof HTMLElement) {
topParent = parent;
}
} else {
topParent = document.documentElement;
}
let xpEvaluator = new XPathEvaluator();
let xpathResult = xpEvaluator.evaluate(
xpath,
topParent,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
);
return xpathResult.singleNodeValue;
}
static getElementsByXPath(xpath, topParent = null) {
if (topParent) {
if (typeof topParent == "string") {
topParent = document.querySelector(topParent);
} else if (parent instanceof HTMLElement) {
topParent = parent;
}
} else {
topParent = document.documentElement;
}
let xpEvaluator = new XPathEvaluator();
let xpathResult = xpEvaluator.evaluate(
xpath,
topParent,
null,
XPathResult.ORDERED_NODE_ITERATOR_TYPE
);
let elements = [];
let node = null;
while (node = xpathResult.iterateNext()) {
elements.push(node);
}
return elements;
}
}