Created
October 30, 2015 08:05
-
-
Save dvdbng/491d5d6cbd968ab70620 to your computer and use it in GitHub Desktop.
Query XPath
This file contains hidden or 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
function queryXPath(expr, ctx, type){ | |
ctx = ctx || document; | |
type = type || XPathResult.ANY_TYPE; | |
var doc = ctx.nodeType === Node.DOCUMENT_NODE ? ctx : ctx.ownerDocument; | |
var nsResolver = doc.createNSResolver(doc.documentElement); | |
var arr = [], i = null; | |
try { | |
expr = ("" + expr).replace(/\bhasClass\(["'](\w+)["']\)/, function(expr, className){ | |
return "contains(concat(' ', normalize-space(@class), ' '), ' " + className + " ')"; | |
}); | |
var res = doc.evaluate(expr, ctx, nsResolver, type, null); | |
type = res.resultType; | |
if(type === XPathResult.NUMBER_TYPE) { | |
return res.numberValue; | |
} else if (type === XPathResult.STRING_TYPE) { | |
return res.stringValue; | |
} else if (type === XPathResult.BOOLEAN_TYPE) { | |
return res.booleanValue; | |
} else if (type === XPathResult.UNORDERED_NODE_ITERATOR_TYPE || type === XPathResult.ORDERED_NODE_ITERATOR_TYPE) { | |
while((i = res.iterateNext()) !== null) { | |
arr.push(i); | |
} | |
return arr; | |
} else if (type === XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE || type === XPathResult.ORDERED_NODE_SNAPSHOT_TYPE) { | |
for (i = 0; i < res.snapshotLength; i++ ) { | |
arr.push(res.snapshotItem(i)); | |
} | |
return arr; | |
} else if (type === XPathResult.ANY_UNORDERED_NODE_TYPE || type === XPathResult.FIRST_ORDERED_NODE_TYPE) { | |
return res.singleNodeValue; | |
} else { | |
throw new Error('Unknown result type ' + type); | |
} | |
} catch(e) { | |
console.log(e); | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment