Created
January 31, 2019 12:51
-
-
Save klintmane/ada857f4c511637fe5bc6c005d4ac56e to your computer and use it in GitHub Desktop.
xpath
This file contains 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
// mozilla ver | |
// https://developer.mozilla.org/en-US/docs/Web/XPath/Snippets#getXPathForElement | |
// ver 2 | |
function getPathTo(element) { | |
if (element.id!=='') | |
return 'id("'+element.id+'")'; | |
if (element===document.body) | |
return element.tagName; | |
var ix= 0; | |
var siblings= element.parentNode.childNodes; | |
for (var i= 0; i<siblings.length; i++) { | |
var sibling= siblings[i]; | |
if (sibling===element) | |
return getPathTo(element.parentNode)+'/'+element.tagName+'['+(ix+1)+']'; | |
if (sibling.nodeType===1 && sibling.tagName===element.tagName) | |
ix++; | |
} | |
} | |
// ver 1 | |
function createXPathFromElement(elm) { | |
var allNodes = document.getElementsByTagName('*'); | |
for (var segs = []; elm && elm.nodeType == 1; elm = elm.parentNode) | |
{ | |
if (elm.hasAttribute('id')) { | |
var uniqueIdCount = 0; | |
for (var n=0;n < allNodes.length;n++) { | |
if (allNodes[n].hasAttribute('id') && allNodes[n].id == elm.id) uniqueIdCount++; | |
if (uniqueIdCount > 1) break; | |
}; | |
if ( uniqueIdCount == 1) { | |
segs.unshift('id("' + elm.getAttribute('id') + '")'); | |
return segs.join('/'); | |
} else { | |
segs.unshift(elm.localName.toLowerCase() + '[@id="' + elm.getAttribute('id') + '"]'); | |
} | |
} else if (elm.hasAttribute('class')) { | |
segs.unshift(elm.localName.toLowerCase() + '[@class="' + elm.getAttribute('class') + '"]'); | |
} else { | |
for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) { | |
if (sib.localName == elm.localName) i++; }; | |
segs.unshift(elm.localName.toLowerCase() + '[' + i + ']'); | |
}; | |
}; | |
return segs.length ? '/' + segs.join('/') : null; | |
}; | |
function lookupElementByXPath(path) { | |
var evaluator = new XPathEvaluator(); | |
var result = evaluator.evaluate(path, document.documentElement, null,XPathResult.FIRST_ORDERED_NODE_TYPE, null); | |
return result.singleNodeValue; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment