Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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