Last active
March 15, 2021 21:42
-
-
Save thebabush/f84642b81de337209bd1 to your computer and use it in GitHub Desktop.
Javascript XPath Helper
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
/** | |
* Helper to make Javascript's XPath calls simpler. | |
* Basically you just need to give a query to the xp function. | |
* Especially useful in manual testing of XPath strings inside a browser's console. | |
* | |
* Example: | |
* xp("//body/text()") | |
* | |
* Author: Paolo Montesel | |
* License: https://opensource.org/licenses/MIT | |
* Copyright 2015 | |
* | |
*/ | |
function xp(path) { | |
var r = []; | |
var x = document.evaluate(path, document, null, XPathResult.ANY_TYPE, null); | |
var item = x.iterateNext(); | |
while (item) { | |
r.push(item); | |
item = x.iterateNext(); | |
} | |
return r; | |
} | |
/** | |
* Helper funciton which returns strings (xp(...) returns text objects). | |
* Useful for JSON.strinfigy(xps(query)); | |
*/ | |
function xps(query) { | |
return xp(query).map(function (el) { return el.textContent; }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment