XPath.js

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 subpar quality (Safari). To install it just include XPath.js and Array.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:

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.

Simple benchmark page, found here. View the page with Firefox which has an reliable native implementation for comparison. The benchmark result show that without the getElementsByTagName optimization our implementation isn’t the fastest, nor the slowest, but atleast it gives the correct result (as/in Firefox anyway).

Documentation

The generated online documentation can be found here.

Changelog

To do

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

Dependancies

Download

License

GNU Lesser General Public License <http://www.gnu.org/licenses/lgpl-3.0.txt>

Author

Henrik Lindqvist <henrik.lindqvist@llamalab.com>

Comment

Enter the code visible here into the Code field
> Delete | Edit