Created
February 6, 2020 02:08
-
-
Save yuta0801/554124199e1aa99c008796da08ad3279 to your computer and use it in GitHub Desktop.
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(element) { | |
if(!element || !element.parentNode) return '' | |
let xpath = getXpath(element.parentNode) + '/' + element.tagName | |
const elements = [] | |
for(const e of element.parentNode.childNodes) { | |
if(e.tagName == element.tagName) elements.push(e) | |
} | |
if(1 < elements.length) { | |
const i = elements.indexOf(element) | |
xpath += '[' + (i+1) + ']' | |
} | |
return xpath.toLowerCase() | |
} | |
function getXpathRec(element, childPath = '') { | |
if(!element || !element.parentNode) return childPath.toLowerCase() | |
const elements = [...element.parentNode.childNodes].filter(e => e.tagName == element.tagName) | |
const xpath = '/' + element.tagName + (1 < elements.length ? `[${elements.indexOf(element) + 1}]` : '') | |
return getXpathRec(element.parentNode, xpath + childPath) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment