Last active
November 27, 2022 11:07
-
-
Save loilo/a7c0df0d4426b9488f843e0436885421 to your computer and use it in GitHub Desktop.
Find DOM nodes via 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
/** | |
* 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