Created
April 18, 2017 14:18
-
-
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
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 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