Skip to content

Instantly share code, notes, and snippets.

@s-shin
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save s-shin/bf11777a20ac2fdd13e2 to your computer and use it in GitHub Desktop.

Select an option

Save s-shin/bf11777a20ac2fdd13e2 to your computer and use it in GitHub Desktop.
// http://stackoverflow.com/q/3454526
function getNodeXPath(node, prefix) {
prefix = prefix ? prefix + ":" : "";
var getNodeName = function(node) {
return {
1: prefix + node.nodeName.toLowerCase(), // instanceof Element
3: "text()"
}[node.nodeType];
};
var paths = [];
// 親へ順番に辿っていく
for (var n = node; n != null; n = n.parentNode) {
// ノードテストの取得
var name = getNodeName(n);
if (!name) {
break;
}
// 同じ階層で、前にいくつ同じタイプのノードがいるかをチェック。
var index = 0;
for (var s = n.previousSibling; s != null; s = s.previousSibling) {
// DOCTYPE宣言は無視する。
if (s.nodeType == Node.DOCUMENT_TYPE_NODE) {
continue;
}
if (name == getNodeName(s)) {
index++;
}
}
paths.unshift([name, "[", index+1, "]"].join(""));
}
return paths.length > 0 ? "/" + paths.join("/") : null;
}
function evaluateXPath(xpath) {
return document.evaluate(xpath, document, function(prefix) {
var c = document.createNSResolver(document).lookupNamespaceURI(prefix);
if (c) return c;
return document.documentElement.namespaceURI;
}, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
}
var el = document.querySelector("body");
var xpath = getNodeXPath(el, "h");
console.log(xpath);
var result = evaluateXPath(xpath);
console.log(result.singleNodeValue);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment