In JavaScript, there is no built-in method to receive all XPath results as an array. For example, with CSS selectors, you can use the “querySelectorAll” method, but there’s no such thing for XPath.
The following code defines it, and usage examples are shown below.
function getElementsByXPath(xpath, parent)
{
let results = [];
let query = document.evaluate(xpath,
parent || document,
null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (let i=0, length=query.snapshotLength; i<length; ++i) {
results.push(query.snapshotItem(i));
}
return results;
}
getElementsByXPath('/html/body//h2')[0].innerText;
getElementsByXPath('/html/body//h2')[1].innerText;