This post goes over how to evaluate an XPath expression with JavaScript in the DOM.
document.evaluate
Use document.evaluate
to evaluate an XPath expression <MY_XPATH>
in the DOM:
document.evaluate('<MY_XPATH>', document, null, XPathResult.ANY_TYPE, null);
For example, to get all buttons containing the text Yes
in the document.body
:
const result = document.evaluate(
'//button[contains(text(), "Yes")]',
document.body,
null,
XPathResult.ANY_TYPE,
null
);
let button;
const buttons = [];
while ((button = result.iterateNext())) {
buttons.push(button);
}
console.log(buttons);
Here’s a helper function that evaluates XPath:
/**
* Evaluate XPath expression.
*
* @param {string} xpathExpression - XPath expression.
* @param {HTMLElement} [contextNode=document] - Context node for the query.
* @returns {HTMLElement[]}
*/
function evaluateXPath(xpathExpression, contextNode = document) {
const result = document.evaluate(
xpathExpression,
contextNode,
null,
XPathResult.ANY_TYPE,
null
);
let element;
const elements = [];
while ((element = result.iterateNext())) {
elements.push(element);
}
return elements;
}
Gist
Miscellaneous
Check out XPath cheatsheet.