Last active
December 6, 2022 00:57
-
-
Save remarkablemark/376477ed8386682cec8644cff5cbb5c9 to your computer and use it in GitHub Desktop.
Evaluate XPath expression in the DOM: https://remarkabl.org/blog/2022/12/05/javascript-evaluate-xpath/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment