Skip to content

Instantly share code, notes, and snippets.

@tao4yu
Last active January 31, 2021 01:01
Show Gist options
  • Save tao4yu/7262010 to your computer and use it in GitHub Desktop.
Save tao4yu/7262010 to your computer and use it in GitHub Desktop.
function XPath(elm) {
for (segs = []; elm && elm.nodeType == 1; elm = elm.parentNode) {
if (elm.hasAttribute('id')) {
segs.unshift('id("' + elm.getAttribute('id') + '")')
return segs.join('/')
}
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
}
<!-- 方法2 -->
function getXPath(element)
{
var xpath = '';
for ( ; element && element.nodeType == 1; element = element.parentNode )
{
var id = $(element.parentNode).children(element.tagName).index(element) + 1;
id > 1 ? (id = '[' + id + ']') : (id = '');
xpath = '/' + element.tagName.toLowerCase() + id + xpath;
}
return xpath;
}
//Gets an XPath for an node
var getNodeXPath = function(node) {
if (node && node.id)
return '//*[@id="' + node.id + '"]';
else
return getNodeTreeXPath(node);
};
var getNodeTreeXPath = function(node) {
var paths = [];
// Use nodeName (instead of localName) so namespace prefix is included (if any).
for (; node && (node.nodeType == 1 || node.nodeType == 3) ; node = node.parentNode) {
var index = 0;
// EXTRA TEST FOR ELEMENT.ID
if (node && node.id) {
paths.splice(0, 0, '/*[@id="' + node.id + '"]');
break;
}
for (var sibling = node.previousSibling; sibling; sibling = sibling.previousSibling) {
// Ignore document type declaration.
if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE)
continue;
if (sibling.nodeName == node.nodeName)
++index;
}
var tagName = (node.nodeType == 1 ? node.nodeName.toLowerCase() : "text()");
var pathIndex = (index ? "[" + (index+1) + "]" : "");
paths.splice(0, 0, tagName + pathIndex);
}
return paths.length ? "/" + paths.join("/") : null;
};
@tao4yu
Copy link
Author

tao4yu commented Nov 8, 2013

还有一个jquery的官方插件:jquery.ellocate.js 提供该功能。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment