Skip to content

Instantly share code, notes, and snippets.

@loilo
Last active November 27, 2022 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loilo/a7c0df0d4426b9488f843e0436885421 to your computer and use it in GitHub Desktop.
Save loilo/a7c0df0d4426b9488f843e0436885421 to your computer and use it in GitHub Desktop.
Find DOM nodes via XPath
/**
* Find nodes via XPath
*
* @param {string} query
* @param {Node} root
* @returns {Node[]}
*/
export function xpath(query, root = document) {
let iterator = document.evaluate(query, document)
try {
let currentNode = iterator.iterateNext()
let nodes = []
while (currentNode) {
nodes.push(currentNode)
currentNode = iterator.iterateNext()
}
return nodes.filter(node => root.contains(node))
} catch (e) {
console.warn(`Document tree modified during iteration ${e}`)
return []
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment