Skip to content

Instantly share code, notes, and snippets.

@Joemires
Forked from barisaydinoglu/getPath.js
Created September 13, 2021 12:57
Show Gist options
  • Save Joemires/84f591d7c473d3fbfa9bf6efedbba2d7 to your computer and use it in GitHub Desktop.
Save Joemires/84f591d7c473d3fbfa9bf6efedbba2d7 to your computer and use it in GitHub Desktop.
getPath.js if for getting a jQuery selector for an element. parsePath.js is for parsing the selector string to path array.
jQuery.fn.extend({
getPath: function () {
var path = "",
node = this;
while (node.length) {
var realNode = node[0],
name = realNode.localName,
id, classNameStr, currentNodeSelector;
if (!name) {
break;
}
currentNodeSelector = name.toLowerCase();
id = realNode.id;
if ( !! id) {
currentNodeSelector = currentNodeSelector + "#" + id;
}
classNameStr = realNode.className;
if ( !! classNameStr) {
currentNodeSelector = currentNodeSelector + "." + classNameStr.split(/[\s\n]+/).join('.');
}
node = node.parent();
path = ">" + currentNodeSelector + path;
}
return path.substr(1);
}
});
// $("#foo").eq(0).getPath()
jQuery.extend({
parsePath: function (pathStr) {
var path = [];
if ( !! pathStr) {
var pathArrayTemp = pathStr.split('>');
for (var p = 0, pl = pathArrayTemp.length; p < pl; p++) {
if ( !! pathArrayTemp[p]) {
var tempObject = {}, classNames = pathArrayTemp[p].split('.');
var idSplit = classNames[0].split('#');
tempObject.node = idSplit[0];
if (idSplit.length > 1) {
tempObject.id = idSplit[1];
}
tempObject.class = [];
for (var c = 1, cl = classNames.length; c < cl; c++) {
if ( !! classNames[c]) {
tempObject.class.push(classNames[c]);
}
}
path.push(tempObject);
}
}
}
return path;
}
});
// $.parsePath("html>body.question-page.new-topbar>div.container>div#content>div>div#herobox-mini>div#hero-content>div#foo")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment