Created
July 18, 2015 19:41
-
-
Save quantuminformation/51820514b48b20a996e9 to your computer and use it in GitHub Desktop.
Get unique query selector for element
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
/** | |
* | |
* @param e event from the DOM that we want to workout the testing path. | |
*/ | |
getUniqueQueryPathToDomEventTarget: function (e) { | |
let hasEmberIdRegex = /ember[\d]+/; | |
if (e.target.id && !hasEmberIdRegex.test(e.target.id)) { | |
return "#" + e.target.id; | |
} else { | |
let path = e.path.reverse().slice(2); //remove the window and document path sections | |
let fullPath = path.map(function (element) { | |
// we need to make each path segment more specific if other siblings of the same type exist | |
let index = findNthChildIndex(element); | |
return element.localName + (index !== -1 ? ':nth-child(' + index + ')' : ''); | |
}).join('>');//join all the segments for the query selector | |
console.log(fullPath); | |
return fullPath; | |
} | |
} | |
}; | |
/** | |
* Gets the nth child index so we can select the element directly | |
* | |
* @param element | |
* @returns {number} | |
*/ | |
function findNthChildIndex(element) { | |
let parent = element.parentNode; | |
if (!parent) {//its the <html> tag | |
return -1; | |
} | |
let children = parent.children; | |
let hasOthers = [].some.call(children, function (elem) { | |
return elem.tagName === element.tagName && elem !== element; | |
}); | |
if (!hasOthers) { | |
return -1; | |
} | |
return Array.from(children).indexOf(element) + 1;//because nth child is 1 indexed | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment