Skip to content

Instantly share code, notes, and snippets.

@gifnksm
Forked from cho45/dollarX.js
Created December 23, 2009 10:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gifnksm/262451 to your computer and use it in GitHub Desktop.
Save gifnksm/262451 to your computer and use it in GitHub Desktop.
// extend version of $X
function $exp (exp, ownerDocument) {
if (!ownerDocument)
ownerDocument = document;
return ownerDocument.createExpression(exp, function (prefix) {
var o = document.createNSResolver(context)(prefix);
if (o) return o;
return (document.contentType == "application/xhtml+xml") ? "http://www.w3.org/1999/xhtml" : "";
});
}
// $X(exp);
// $X(exp, context);
// $X(exp, type);
// $X(exp, context, type);
function $X (exp, context, type /* want type */) {
if (context !== null && !(context instanceof Node)) {
type = context;
context = null;
}
if (!context) context = document;
if (typeof exp == 'string' || exp instanceof String)
exp = $exp(exp, context.ownerDocument || context);
switch (type) {
case Number: type = XPathResult.NUMBER_TYPE; break;
case String: type = XPathResult.STRING_TYPE; break;
case Boolean: type = XPathResult.BOOLEAN_TYPE; break;
case Array: type = XPathResult.ORDERED_NODE_SNAPSHOT_TYPE; break;
case Node: type = XPathResult.FIRST_ORDERED_NODE_TYPE; break;
}
var result = exp.evaluate(context, type, null), ret, i, len;
switch (result.resultType) {
case XPathResult.NUMBER_TYPE: return result.numberValue;
case XPathResult.STRING_TYPE: return result.stringValue;
case XPathResult.BOOLEAN_TYPE: return result.booleanValue;
case XPathResult.UNORDERED_NODE_ITERATOR_TYPE:
case XPathResult.ORDERED_NODE_ITERATOR_TYPE:
ret = []; i = null;
while ((i = result.iterateNext()) != null)
ret.push(i);
return ret;
case XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE:
case XPathResult.ORDERED_NODE_SNAPSHOT_TYPE:
ret = [];
for (i = 0, len = result.snapshotLength; i < len; i++)
ret.push(result.snapshotItem(i));
return ret;
case XPathResult.FIRST_ORDERED_NODE_TYPE: return result.singleNodeValue;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment