2006/01/02

Prototype-style shortcut function for XPath expressions

Background: using Prototype is allegedly like using crack - immediately gratifying and bad for the whole application. The wisdom of using for(in) notwithstanding, I dunno.

Anyway, the nicest things of all in Prototype are the shortcuts: $() and $F(), which make my life much more chilled out (pass the pipe dude,) and so I hereby introduce an equivalent for XPath munging: $X().

This needs Sarissa to paper over the differences between IE and FF for this to work. Needless to say, Safari users can go swivel until Apple gets of their butt and improves their XSLT support. </flamebait>. The commented out 'Logger' is using Lumberjack syntax.
function $X(xPathExpr, ctxNode, doc) {
if(!ctxNode) {
ctxNode = document;
}

if(!doc) {
if(ctxNode instanceof Document) {
doc = ctxNode;
} else {
doc = ctxNode.ownerDocument;
}
}

var result = doc.selectNodes(xPathExpr, ctxNode);

if(result == null) {
//Logger.debug("no match for "+xPathExpr);
return null;
}

if(result.length == 1) return result[0];

return result;
}
Usage is as follows:
  • $X("//p") returns all paras in a document.
  • $("//p[@id=foo]") returns one para with id foo.
  • arg[1] optionally specifies the node context (relative root)
  • arg[2] can specify a different document to work on, for example one retrieved via XMLHttpRequest.

No comments: