Mozilla implements much of the DOM 3 XPath. This allows XPath expressions to be run against both HTML and XML documents.
var xpathResult = document.evaluate(xpathExpression, contextNode, namespaceResolver, resultType, result);
The evaluate function takes a total of five arguments:
xpathExpression: A string containing the XPath expression to be evaluated.
contextNode: A node in the document against which the XPath expression should be evaluated. The document node is the most commonly used.
- namespaceResolver: A function that will be passed any namespace prefixes from xpathExpression and return a string representing the namespace URI associated with that prefix. This enables conversion between the prefixes used in the XPath expressions and the (possibly different) prefixes used in the document. The most commonly used value for this is
null, which is used for HTML documents or when no namespace prefixes are used.
- resultType: A numeric constant (or named constant properties, such as XPathResult.ANY_TYPE) that corresponds to the result of type XPathResult to return. (defined in the relevaant section of the XPath Spec). The most commonly passed constant is XPathResult.ANY_TYPE which will return the results of the XPath expression as the most natural type.
- result: An existing XPathResult to use for the results. Passing null causes a new XPathResult to be created.
A Simple Example
To extract the level 2 headings of a HTML document using XPath the XPath Expression is simply
//h2. The full code for this is then:
var headings = document.evaluate('//h2', document, null, XPathResult.ANY_TYPE, null);
Notice that, since HTML does not have namespaces, we have passed
null for the
namespaceResolver. Since we wish to search over the entire document for headings, we have used the document object itself as the contextNode.