Created
December 15, 2019 18:29
-
-
Save ademilter/9396af93c609264a939d2df5fa2e6b15 to your computer and use it in GitHub Desktop.
selected node get xpath
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function getXPath(nodeElem) { | |
| const parts = []; | |
| while (nodeElem && nodeElem.nodeType === Node.ELEMENT_NODE) { | |
| let nbOfPreviousSiblings = 0; | |
| let hasNextSiblings = false; | |
| let sibling = nodeElem.previousSibling; | |
| while (sibling) { | |
| if ( | |
| sibling.nodeType !== Node.DOCUMENT_TYPE_NODE && | |
| sibling.nodeName === nodeElem.nodeName | |
| ) { | |
| nbOfPreviousSiblings++; | |
| } | |
| sibling = sibling.previousSibling; | |
| } | |
| sibling = nodeElem.nextSibling; | |
| while (sibling) { | |
| if (sibling.nodeName === nodeElem.nodeName) { | |
| hasNextSiblings = true; | |
| break; | |
| } | |
| sibling = sibling.nextSibling; | |
| } | |
| const prefix = nodeElem.prefix ? nodeElem.prefix + ":" : ""; | |
| const nth = | |
| nbOfPreviousSiblings || hasNextSiblings | |
| ? `[${nbOfPreviousSiblings + 1}]` | |
| : ""; | |
| parts.push(prefix + nodeElem.localName + nth); | |
| nodeElem = nodeElem.parentNode; | |
| } | |
| return parts.length ? "/" + parts.reverse().join("/") : ""; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment