XPath.js

JavaScript implementation of XML Path Language and DOM Level 3 XPath

JavaScript implementation of XML Path Language (XPath) Version 1.0 and DOM Level 3 XPath. For use where native XPath is unavailable (Internet Explorer) or of sub-par quality (Safari). To install it just include xpath-min.js and array-min.js. Safari’s native XPath is replaced since it’s very buggy.

So what’s special about this implementation? The file size, only ~15 K minified! It’s definitely the smallest of them all, minified or not. Why spend bandwidth on stuff that might already be built-in. Other implementations known:

  • Cybozu (~41 K minified)
  • Google (~59 K minified)
  • McCormack (~87 K minified)
  • Any other out there? Contact me if you know any.

Standard DOM Level 3 XPath usage:

for (var r = document.evaluate('//H2', document, null, 4, null), n; n = r.iterateNext();) {
  // color all level 2 headers red
  n.style.color = 'red';
}

Beware that when used in Internet Explorer with expressions resulting in attribute nodes (i.e //attribute::*) the nodes may not be correctly ordered nor unique. This is caused by the lack of ownerElement, which makes compareDocumentPosition unreliable.

You can test it out yourself here. The test-page uses the native implementation if available, so view it with Internet Explorer or Safari where our implementation is used.

Changelog

  • 2008-06-17 v0.5: Fix for Firefox 3’s improved compareDocumentPosition which seems to return correct result when comparing Attr nodes.
  • 2008-05-29 v0.4: Fixed the performance issue below. Now using nodeValue instead of specified only on selected and value attributes to avoid some of the data conversion slow down.
  • 2008-05-21 v0.3: Work-around for Internet Explorer’s buggy specified property in Attr nodes, using nodeValue instead. Weird performance loss, IE seems to convert data for this property.
  • 2008-04-11 v0.2: Fully implemented DOM Level 3 XPath, thus replacing the selectNodes and selectSingleNode syntax. Boosted compareDocumentPosition performance using Internet Explorer’s sourceIndex and contains.
  • 2008-03-07 v0.1: Initial public release.

To do

  • Optimize node selection using getElementsByTagName wherever possible.
  • Implement variables.
  • Implement the namespace axis. Easily done, but since Firefox doesn’t support it, I’ve ignored it.

Documentation

The generated online documentation can be found here.

Download

Dependancies

  • None, except the Array functions added in JavaScript version 1.6. If the functions isn’t supported in your target browser (i.e Internet Explorer), you’ll need to implement them yourself or include Array.js (1.3 K)

License

Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0>

Author

Henrik Lindqvist <henrik.lindqvist@llamalab.com>