Skip to content

Instantly share code, notes, and snippets.

@socheatsok78
Created September 19, 2018 02:58
Show Gist options
  • Save socheatsok78/89c29d452a1ddb81ebaee498ae6809a4 to your computer and use it in GitHub Desktop.
Save socheatsok78/89c29d452a1ddb81ebaee498ae6809a4 to your computer and use it in GitHub Desktop.
VueXPath - $x(path) returns an array of DOM elements that match the given XPath expression.

VueXPath

$x(path) returns an array of DOM elements that match the given XPath expression.

Requirement

npm install wicked-good-xpath

Install

import Vue from 'vue';
import VueXPath from 'VueXPath'
Vue.use(VueXPath)

Usage

// Within your Vue component
this.$x('//*[@id="app"]');
// [div#app]
import wgxpath from 'wicked-good-xpath';
/**
* Unofficial $x XPath Selector from Google Chrome DevTools
* @param {string} xpath XPath expression
* @param {HTMLElement|object} startNode Element or Node from which to search for elements
*/
function XPath(xpath, startNode) {
let nodes = [];
try {
let doc = (startNode && startNode.ownerDocument) || window.document;
let results = doc.evaluate(xpath, startNode || doc, null, XPathResult.ANY_TYPE, null);
let node;
while (node = results.iterateNext()) {
nodes.push(node);
}
} catch (e) {
throw e;
}
return nodes;
}
/**
* VueXPath Selector
* @documentation https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#xpath
* @borrows https://gist.github.com/romer/1388065, https://github.com/google/wicked-good-xpath
*/
const VueXPath = {
install: (Vue) => {
wgxpath.install();
// Register instance method
Vue.prototype.$x = XPath;
}
}
// Export VueXPath by default
export default VueXPath;
// Export modules
export { wgxpath, XPath }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment