Firebug可以做到这一点,它是开源BSD的,因此您可以重复使用它们的实现,而无需任何库。
第三方这是上面链接源的摘录。以防万一上面的链接会改变。请检查源以从更改和更新或提供的完整功能集中受益。
Xpath.getElementXPath = function(element){ if (element && element.id) return '//*[@id="' + element.id + '"]'; else return Xpath.getElementTreeXPath(element);};
上面的代码调用此函数。注意,我添加了一些换行符以避免水平滚动条
Xpath.getElementTreeXPath = function(element){ var paths = []; // Use nodeName (instead of localName) // so namespace prefix is included (if any). for (; element && element.nodeType == Node.ELEMENT_NODE; element = element.parentNode) { var index = 0; var hasFollowingSiblings = false; for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling) { // Ignore document type declaration. if (sibling.nodeType == Node.document_TYPE_NODE) continue; if (sibling.nodeName == element.nodeName) ++index; } for (var sibling = element.nextSibling; sibling && !hasFollowingSiblings; sibling = sibling.nextSibling) { if (sibling.nodeName == element.nodeName) hasFollowingSiblings = true; } var tagName = (element.prefix ? element.prefix + ":" : "") + element.localName; var pathIndex = (index || hasFollowingSiblings ? "[" + (index + 1) + "]" : ""); paths.splice(0, 0, tagName + pathIndex); } return paths.length ? "/" + paths.join("/") : null;};
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)