Created
September 18, 2014 10:26
-
-
Save MNBuyskih/142170c30f69e95d8b5c to your computer and use it in GitHub Desktop.
Get full path of element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.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