XPath in JavaScript

Here is an implementation of XPath 1.0 in JavaScript, which should run in exactly the same way in IE and Mozilla. It's not completely tested but it seems to work with the few tests I've run. It is released under the GNU Lesser General Public License as published by the Free Software Foundation. Please let me know if there are any bugs.

Example for counting all links on your document is just one XPath query:

var linkCount = document.evaluate(“count(//a[@href])“, document, null, XPathResult.NUMBER_TYPE, null).getNumberValue();

And for getting a list of all images without an alt tag:

var imgIterator = document.evaluate(“//img[not(@alt)]“, document, null, XPathResult.ANY_TYPE, null);

So for finding a first LI element of al UL tags:

var firstLiIterator = document.evaluate(“//ul/li[1]“, document, null, XPathResult.ANY_TYPE, null);

Putting it all together we can create the following function:

function showIterator(title, result)
var s = title;
var item;
while(item = result.iterateNext())
s += "<div class=\"XPathResultItem\">" + (item.nodeType == 1 ? item.innerHTML.replace(/</g, "&lt;").replace(/>/g, "&gt;") : item.nodeValue) + "</div>";

// Evaluate 1
var result = document.evaluate("//div[@class='Test']", document, null, XPathResult.STRING_TYPE, null);
document.write("<h1>\"//div[@class='Test']\" as String</h1>" + result.getStringValue());

// Evaluate 2
document.evaluate("//img[@width < 100]/@height", document, null, XPathResult.NUMBER_TYPE, result);
document.write("<h1>\"//img[@width < 100]/@height\" as Number</h1>" + result.getNumberValue());

// Evaluate 3
"<h1>\"//div[@class='Test']\" in context of document</h1>",
document.evaluate("//div[@class='Test']", document, null, XPathResult.ANY_TYPE, result)

// Evaluate 4
"<h1>\"div[@class='Test']\" in context of a specific node (id=\"ContextNodeTest\")</h1>",
document.evaluate("div[@class='Test']", document.getElementById("ContextNodeTest"), null, XPathResult.ANY_TYPE, result)

// Evaluate 5
"<h1>\"//div/@class\": Retrieve Attribute Values</h1>",
document.evaluate("//div/@class", document, null, 0, result)

// Evaluate 6
var result = document.evaluate("count(//span[@class='Number'])", document, null, XPathResult.NUMBER_TYPE, null);
document.write("<h1>\"count(//span[@class='Number'])\" as Number</h1>" + result.getNumberValue());

Page navigation