Skip to content

Instantly share code, notes, and snippets.

@thebabush
Last active March 15, 2021 21:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thebabush/f84642b81de337209bd1 to your computer and use it in GitHub Desktop.
Save thebabush/f84642b81de337209bd1 to your computer and use it in GitHub Desktop.
Javascript XPath Helper
/**
* 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