Skip to content

Instantly share code, notes, and snippets.

@brunnerh
Created May 3, 2019 18:11
Show Gist options
  • Save brunnerh/9fa0f59b0f83f54decd0ac02a719ac39 to your computer and use it in GitHub Desktop.
Save brunnerh/9fa0f59b0f83f54decd0ac02a719ac39 to your computer and use it in GitHub Desktop.
Iterable document.evaluate wrapper.
/**
* Executes an XPath expression returning an iterable node list.
* @param {string} expression XPath expression.
* @param {Node} node Optional context node for query. Default is document element.
* @param {XPathNSResolver | ((prefix: string) => string | null) | null} nsResolver Optional namespace resolver function.
* @returns {Iterator<Node>} Result nodes iterator.
*/
function* xpath(expression, node = document.documentElement, nsResolver = null)
{
const xPathResult = document.evaluate(
expression,
node,
nsResolver,
XPathResult.ANY_TYPE,
null
);
while (true)
{
const result = xPathResult.iterateNext();
if (result == null)
break;
yield result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment