Skip to content

Instantly share code, notes, and snippets.

@asad01304
Last active January 2, 2016 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asad01304/8356438 to your computer and use it in GitHub Desktop.
Save asad01304/8356438 to your computer and use it in GitHub Desktop.
the following function calculates a dom's jQ selector
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