Skip to content

Instantly share code, notes, and snippets.

@vace
Created April 18, 2017 14:18
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 vace/153224d14d30b139f0245bf7e59ff685 to your computer and use it in GitHub Desktop.
Save vace/153224d14d30b139f0245bf7e59ff685 to your computer and use it in GitHub Desktop.
getUniquePath(document.querySelector('img')) => html>body>div>div>div>div:nth-child(2)>table>tbody>tr>th:nth-child(2)>div>img
function getUniquePath(element){
if(element.nodeType !== Node.ELEMENT_NODE){
throw new Error('element must be element node')
}
if(element.id){
return '#' + element.id
}
var path = ''
while(element){
var name = element.localName
if(!name){
break;
}
var parent = element.parentNode
if(parent){
var nodeList = parent.childNodes,
node,
idx = 0
for(var i = 0; i < nodeList.length; i++){
node = nodeList[i]
if(node.localName === name){
idx += 1
}
if(node === element){
break
}
}
if(idx > 1){
name += ':nth-child(' + idx + ')';
}
}
path = name + (path ? '>' + path : '');
element = parent
}
return path
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment