Last active
January 2, 2016 20:19
-
-
Save asad01304/8356438 to your computer and use it in GitHub Desktop.
the following function calculates a dom's jQ selector
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
function getXPaths (dom){ | |
//If dom has id and making sure no other dom has the same id | |
function hasUniquId (dom){ | |
return (dom.id && dom.id.length) && ($("[id="+dom.id+"]").size() > 1); | |
} | |
//If dom has any siblings , if yes then it's position | |
function getPositionInSiblings(dom){ | |
var tagName = dom.tagName.toLowerCase() , | |
childs = $(dom.parentNode).find(tagName), | |
tmpKlss = 'tmpKlss_' + Math.random().toString().replace('.','') ; | |
$(dom).addClass(tmpKlss); | |
for(var i = 0; i< childs.size(); i++){ | |
var tmpOb = childs[i]; | |
if($(tmpOb).hasClass(tmpKlss)){ | |
$(tmpOb).removeClass(tmpKlss); | |
return i; | |
} | |
} | |
return false; | |
} | |
function getMyQuery(dom){ | |
//If body, then tag itself good enough as selector | |
if(dom.nodeName.toLowerCase() == 'body'){ | |
return 'body'; | |
} | |
//If dom has unique id, then selector is #id | |
if(hasUniquId (dom)) { | |
return '#' + dom.id; | |
} | |
//recursively calculate doms selector | |
var i = getPositionInSiblings(dom); | |
return ( i === false) ? | |
getMyQuery(dom.parentNode) + ' ' + dom.tagName : | |
getMyQuery(dom.parentNode) + ' ' + dom.tagName + ':eq(' + i + ')'; | |
} | |
return getMyQuery(dom); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment