Last active
November 11, 2016 14:30
-
-
Save jsnjack/3b9d5d14adb79adcaa01 to your computer and use it in GitHub Desktop.
Return unique selector of the element
This file contains hidden or 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
/*globals document*/ | |
var element = document.querySelector('a'); | |
function positionInNodeList(element, nodeList) { | |
for (var i = 0; i < nodeList.length; i++) { | |
if (element === nodeList[i]) { | |
return i; | |
} | |
} | |
return - 1; | |
} | |
function getUniqueSelector(element) { | |
var tagName = element.localName, | |
selector, index, matches; | |
// document.querySelectorAll("#id") returns multiple if elements share an ID | |
if (element.id && document.querySelectorAll('#' + element.id).length === 1) { | |
return '#' + element.id; | |
} | |
// Inherently unique by tag name | |
if (tagName === 'html') { | |
return 'html'; | |
} | |
if (tagName === 'head') { | |
return 'head'; | |
} | |
if (tagName === 'body') { | |
return 'body'; | |
} | |
// We might be able to find a unique class name | |
if (element.classList.length > 0) { | |
for (var i = 0; i < element.classList.length; i++) { | |
// Is this className unique by itself? | |
selector = '.' + element.classList.item(i); | |
matches = document.querySelectorAll(selector); | |
if (matches.length === 1) { | |
return selector; | |
} | |
// Maybe it's unique with a tag name? | |
selector = tagName + selector; | |
matches = document.querySelectorAll(selector); | |
if (matches.length === 1) { | |
return selector; | |
} | |
// Maybe it's unique using a tag name and nth-child | |
index = positionInNodeList(element, element.parentNode.children) + 1; | |
selector = selector + ':nth-child(' + index + ')'; | |
matches = document.querySelectorAll(selector); | |
if (matches.length === 1) { | |
return selector; | |
} | |
} | |
} | |
// Not unique enough yet. As long as it's not a child of the document, | |
// continue recursing up until it is unique enough. | |
if (element.parentNode !== document) { | |
index = positionInNodeList(element, element.parentNode.children) + 1; | |
selector = getUniqueSelector(element.parentNode) + ' > ' + | |
tagName + ':nth-child(' + index + ')'; | |
} | |
return selector; | |
} | |
console.log(getUniqueSelector(element)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment