docs.rodeo

MDN Web Docs mirror

Document: evaluate() method

{{ ApiRef("DOM") }} 

The evaluate() method of the {{domxref("Document")}}  interface selects elements based on the XPath expression given in parameters.

XPath expressions can be evaluated on both HTML and XML documents.

Syntax

evaluate(xpathExpression, contextNode, namespaceResolver, resultType, result)

Parameters

Return value

An {{domxref("XPathResult")}}  linking to the selected nodes. If result was null, it is a new object, if not, it is the same object as the one passed as the result parameter.

Examples

Finding all H2 headings by XPath

const headings = document.evaluate(
  "/html/body//h2",
  document,
  null,
  XPathResult.ANY_TYPE,
  null,
);
/* Search the document for all h2 elements.
 * The result will likely be an unordered node iterator. */
let thisHeading = headings.iterateNext();
let alertText = "Level 2 headings in this document are:\n";
while (thisHeading) {
  alertText += `${thisHeading.textContent}\n`;
  thisHeading = headings.iterateNext();
}
alert(alertText); // Alerts the text of all h2 elements

Note, in the above example, a more verbose xpath is preferred over common shortcuts such as //h2. Generally, more specific xpath selectors, as in the above example, usually give a significant performance improvement, especially on very large documents. This is because the evaluation of the query does not waste time visiting unnecessary nodes. Using // is generally slow as it visits every node from the root and all subnodes looking for possible matches.

Further optimization can be achieved by careful use of the context parameter. For example, if you know the content you are looking for is somewhere inside the body tag, you can use this:

document.evaluate(".//h2", document.body, null, XPathResult.ANY_TYPE, null);

Notice in the above document.body has been used as the context instead of document so the xpath starts from the body element. (In this example, the "." is important to indicate that the querying should start from the context node, document.body. If the “.” was left out (leaving //h2) the query would start from the root node (html) which would be more wasteful.)

See Introduction to using XPath in JavaScript for more information.

Getting element by xml:id

This function is a replacement for {{domxref("Document.getElementById()")}}  for when you need to search by xml:id instead.

function getElementByIdWrapper(xmlDoc, id) {
  return xmlDoc.evaluate(
    `//*[@xml:id="${id}"]`,
    xmlDoc,
    () => "http://www.w3.org/XML/1998/namespace",
    XPathResult.FIRST_ORDERED_NODE_TYPE,
    null,
  ).singleNodeValue;
}

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN