Skip to content

Instantly share code, notes, and snippets.

@crobinson42
Created April 7, 2017 23:39
Show Gist options
  • Select an option

  • Save crobinson42/2968dcb8046651db60f91c2bcf7feb2f to your computer and use it in GitHub Desktop.

Select an option

Save crobinson42/2968dcb8046651db60f91c2bcf7feb2f to your computer and use it in GitHub Desktop.
xPath selector creator
// Hover your mouse over an element, then press ctrl + spacebar, the xPath selector will be console logged
var getElementXPath = function(element) {
if (element && element.id)
return '//*[@id="' + element.id + '"]'
else
return getElementTreeXPath(element)
}
var getElementTreeXPath = function(element) {
var paths = [];
// Use nodeName (instead of localName) so namespace prefix is included (if any).
for (; element && element.nodeType == 1; element = element.parentNode) {
var index = 0;
// EXTRA TEST FOR ELEMENT.ID
if (element && element.id) {
paths.splice(0, 0, '/*[@id="' + element.id + '"]');
break;
}
for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling) {
// Ignore document type declaration.
if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE)
continue;
if (sibling.nodeName == element.nodeName)
++index;
}
var tagName = element.nodeName.toLowerCase();
var pathIndex = (index ? "[" + (index+1) + "]" : "");
paths.splice(0, 0, tagName + pathIndex);
}
return paths.length ? "/" + paths.join("/") : null;
}
document.addEventListener('mouseover', e => window.currentMouseOverElement = e.target)
document.addEventListener('keydown', e => {
if (e.keyCode === 32 && e.ctrlKey) {
console.log(getElementXPath(window.currentMouseOverElement))
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment