Skip to content

Instantly share code, notes, and snippets.

@MNBuyskih
Created September 18, 2014 10:26
Show Gist options
  • Save MNBuyskih/142170c30f69e95d8b5c to your computer and use it in GitHub Desktop.
Save MNBuyskih/142170c30f69e95d8b5c to your computer and use it in GitHub Desktop.
Get full path of element
$.fn.getPath = function () {
var $this = $(this), _parents = $this.parents(), parents = [], getIndex = function (node, className) {
var name = node.get(0).tagName.toLowerCase(), parent = node.parent(), siblings = parent.children(name + className);
if (siblings.length > 1) {
return ':nth-child(' + (siblings.index(node) + 1) + ')';
}
return '';
}, getClass = function (className) {
className = $.trim(className);
if (!className) return '';
return "." + className.replace(/\s/gi, ".")
}, getTag = function (realNode) {
return realNode.tagName.toLowerCase()
};
parents.push(this.get(0));
$.each(_parents, function (n, el) {
parents.push(el);
});
var root, selector = [];
$.each(parents, function (n, el) {
var $el = $(el), id = $el.attr('id'), tagName = getTag(el), className = $el.attr('class'),
prepareClass = getClass(className), index = getIndex($el, prepareClass);
if (id) {
root = '#' + id;
selector.push(root);
} else if (className) {
selector.push(tagName + prepareClass + index);
} else {
selector.push(tagName + index);
}
return !root;
});
return selector.reverse().join(' > ');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment