Last active
August 29, 2015 14:13
-
-
Save jtyjty99999/61c4a2e51126f7c819fb to your computer and use it in GitHub Desktop.
getCSSPath
This file contains hidden or 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
var getCSSPath = function(elem, detail) { | |
var detail = detail || {}; | |
var path = '', nextElem = elem; | |
if (detail.withAttrs) { | |
path += convertAttrsToCSS(elem); | |
} | |
if (detail.withIndex) { | |
path += ':nth-child(' + getSiblingIndex(elem) + ')'; | |
} | |
if (elem.getAttribute('id')) | |
return '#' + elem.getAttribute('id'); | |
while (nextElem) { | |
var parent = nextElem.parentNode; | |
if (parent == document) { | |
if (!detail.withClass) { | |
return getCSSPath(elem, {withClass : true}); | |
} | |
if (!detail.withAttrs) { | |
return getCSSPath(elem, {withClass : true, withAttrs : true}); | |
} | |
if (!detail.withIndex) { | |
return getCSSPath(elem, {withClass : true, withAttrs : true, withIndex : true}); | |
} | |
return "unable to find a unique CSS path: (" + path + ")"; | |
} | |
var subPath = nextElem.tagName; | |
if (nextElem.className && detail.withClass) | |
subPath += '.' + [].slice.call(nextElem.classList).map(String).join('.'); | |
(elem != nextElem) && (subPath += ' > '); | |
path = subPath + path; | |
if (document.querySelectorAll(path).length == 1) { | |
return path; | |
} | |
if (!document.querySelectorAll(path).length) { | |
throw Error("no matches for elem: " + elem + " path: " + path); | |
} | |
nextElem = parent; | |
} | |
return path; | |
function getSiblingIndex(elem) { | |
var index = 1, prevNode; | |
while(prevNode = elem.previousSibling) { | |
(prevNode.nodeType == 1) && index++; | |
elem = elem.previousSibling; | |
} | |
return index; | |
} | |
function convertAttrsToCSS(elem) { | |
var ignoreList = ['class']; | |
var attrs = [].slice.call(elem.attributes).filter(function(attr) { | |
return ignoreList.indexOf(attr.nodeName) < 0 ; | |
}); | |
return attrs.map(function(a){ | |
return ['[',a.nodeName,'="',a.nodeValue,'"]'].join(''); | |
}).join(''); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment