Skip to content

Instantly share code, notes, and snippets.

@yuta0801
Created February 6, 2020 02:08
Show Gist options
  • Save yuta0801/554124199e1aa99c008796da08ad3279 to your computer and use it in GitHub Desktop.
Save yuta0801/554124199e1aa99c008796da08ad3279 to your computer and use it in GitHub Desktop.
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