MCPcopy Create free account
hub / github.com/deta/surf / getXPath

Function getXPath

packages/web-parser/src/annotations/xpath.ts:1–27  ·  view source on GitHub ↗
(node: Node)

Source from the content-addressed store, hash-verified

1export function getXPath(node: Node): string | undefined {
2 if (node.nodeType === Node.TEXT_NODE) {
3 let count: number = 0
4 let sibling: Node | null = node.previousSibling
5
6 while (sibling) {
7 if (sibling.nodeType === Node.TEXT_NODE) {
8 count++
9 }
10 sibling = sibling.previousSibling
11 }
12
13 return getXPath(node.parentNode as Node) + '/text()[' + (count + 1) + ']'
14 } else if (node.nodeType === Node.ELEMENT_NODE) {
15 let elem: Element = node as Element
16 if (elem.id && document.getElementById(elem.id) === elem) {
17 return 'id("' + elem.id + '")'
18 } else if (elem === document.documentElement) {
19 return elem.tagName.toLowerCase()
20 } else {
21 let siblingIndex: number = getSiblingIndex(elem)
22 return `${getXPath(elem.parentNode as Node)}/${elem.tagName.toLowerCase()}[${siblingIndex}]`
23 }
24 } else {
25 return
26 }
27}
28
29function getSiblingIndex(node: Node): number {
30 let index: number = 1 // XPath is 1-indexed

Callers 1

getRangeDataFunction · 0.90

Calls 1

getSiblingIndexFunction · 0.85

Tested by

no test coverage detected