JavaScript XPath Implementation

XPath is a language for finding information in documents. XPath is generally used to navigate through elements and attributes in an XML document but can also be used as a powerful query language.

Why does XPath matters? XPath is a major element in the W3C's XSLT standard - and XQuery and XPointer are both built on XPath expressions. Combined with AJAX, XPath can be used to reshape / augment your HTML code using DOM on the fly.

Have you ever wondered why there is no support for XPath built-in? Actually, there is; Mozilla has a pretty solid support of the DOM Level 3 XPath through the document.evaluate method:

document.evaluate(expression, contextNode, resolver, type, result);

By default, this method returns an iterator, which can be worked through as:

while(item = iterator.iterateNext())
// do something with item

The iterator will return null once all items are exhausted. By modifying the type parameter, you can make the method return other types such as string, boolean, number, and a snapshot. Snapshot is kind of like an iterator, except the DOM is free to change while the snapshot still exists. If you try to do the same with the iterator, it will throw an exception.

Current Internet Explorer support for XPath in JavaScript is limited to the following two cases:

1) As call to an Msxml.DOMDocument object, created using the new ActiveXObject statement.

2) If an HTML document was generated as a result of a client-side XSL transformation from an XML file.

Neither case offers us a solution if we want to use XPath in a plain vanilla HTML. This JavaScript library was created to provide whole new level of flexibility and just plain coding convenience for JavaScript developers.

Page navigation