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:
- 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.
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
- 2008-06-17 v0.5: Fix for Firefox 3’s improved
compareDocumentPositionwhich seems to return correct result when comparingAttrnodes. - 2008-05-29 v0.4: Fixed the performance issue below. Now using
nodeValueinstead ofspecifiedonly onselectedandvalueattributes to avoid some of the data conversion slow down. - 2008-05-21 v0.3: Work-around for Internet Explorer’s buggy
specifiedproperty inAttrnodes, usingnodeValueinstead. Wierd performance loss, IE seems to convert data for this property. - 2008-04-11 v0.2: Fully implemented DOM Level 3 XPath, thus replacing the
selectNodesandselectSingleNodesyntax. BoostedcompareDocumentPositionperformance using Internet Explorer’ssourceIndexandcontains. - 2008-03-07 v0.1: Initial public release.
To do
- Optimize node selection using
getElementsByTagNamewherever possible. - Implement variables.
- Implement the
namespaceaxis. Easily done, but since Firefox doesn’t support it, I’ve ignored it.
Dependancies
- None, except the
Arrayfunctions 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)
Download
License
GNU Lesser General Public License <http://www.gnu.org/licenses/lgpl-3.0.txt>
Author
Henrik Lindqvist <henrik.lindqvist@llamalab.com>