MCPcopy Create free account
hub / github.com/bermi/element-xpath / getElementXpath

Function getElementXpath

element-xpath.js:19–63  ·  view source on GitHub ↗
(el, callback)

Source from the content-addressed store, hash-verified

17
18 // Create a safe reference to the getElementXpath object for use below.
19 getElementXpath = function (el, callback) {
20 var err, result, nodes, i, n, segments, siblings, id_count;
21 try {
22 if (callback && (typeof callback !== "function")) {
23 throw new Error("Invalid callback supplied");
24 }
25
26 // We need to get all the tags on the document,
27 nodes = getElementXpath.getNodes(el);
28
29 segments = [];
30 while (el && el.nodeType === 1) {
31 if (el.hasAttribute("id")) {
32 segments = addIdSegments(el, nodes, segments);
33 if (typeof segments === 'string') {
34 result = segments;
35 break;
36 }
37 } else if (el.hasAttribute("class")) {
38 segments = addClassSegment(el, nodes, segments);
39 } else {
40 segments = addSiblingSegment(el, nodes, segments);
41 }
42 el = el.parentNode;
43 }
44
45 if (!result && segments.length) {
46 result = "/" + segments.join("/");
47 }
48
49 } catch (err) {
50 // On sync mode the error will be included on the callback
51 // remove if only async is supported
52 if (!callback) {
53 throw err;
54 }
55 }
56
57 // Async mode, remove condition if only async is supported
58 if (callback) {
59 callback(err, result);
60 } else {
61 return result;
62 }
63 };
64
65
66 // Run getElementXpath in *noConflict* mode, returning the `getElementXpath`

Callers 1

test.jsFile · 0.85

Calls 3

addIdSegmentsFunction · 0.85
addClassSegmentFunction · 0.85
addSiblingSegmentFunction · 0.85

Tested by

no test coverage detected